diff --git a/sdk/peering/azure-mgmt-peering/_meta.json b/sdk/peering/azure-mgmt-peering/_meta.json index 0b99ef6e37e6..ba5c9ef48abe 100644 --- a/sdk/peering/azure-mgmt-peering/_meta.json +++ b/sdk/peering/azure-mgmt-peering/_meta.json @@ -1,8 +1,11 @@ { - "autorest": "3.3.0", - "use": "@autorest/python@5.6.6", - "commit": "e304f0d89247ec7d983167f5cfa6ed975a5e8a12", + "commit": "b4e9ccd87abbf3ccdfbf4e886b2a9c2c46e8e645", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/peering/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --track2 --use=@autorest/python@5.6.6 --version=3.3.0", + "autorest": "3.9.2", + "use": [ + "@autorest/python@6.2.1", + "@autorest/modelerfour@4.24.3" + ], + "autorest_command": "autorest specification/peering/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.2.1 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/peering/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/__init__.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/__init__.py index c0f79fcd0b4f..c42f38961cb4 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/__init__.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/__init__.py @@ -10,10 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['PeeringManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PeeringManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_configuration.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_configuration.py index 4bfcbfb84f3a..4b04cccd6972 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_configuration.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_configuration.py @@ -6,66 +6,70 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +import sys +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class PeeringManagementClientConfiguration(Configuration): +class PeeringManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for PeeringManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. + :param subscription_id: The Azure subscription ID. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(PeeringManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-10-01") # type: Literal["2022-10-01"] + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(PeeringManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2019-08-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-peering/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-peering/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_metadata.json b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_metadata.json deleted file mode 100644 index 6edfed47f4b3..000000000000 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_metadata.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "chosen_version": "2019-08-01-preview", - "total_api_version_list": ["2019-08-01-preview"], - "client": { - "name": "PeeringManagementClient", - "filename": "_peering_management_client", - "description": "Peering Client.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": 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\": [\"PeeringManagementClientConfiguration\"], \"._operations_mixin\": [\"PeeringManagementClientOperationsMixin\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"PeeringManagementClientConfiguration\"], \"._operations_mixin\": [\"PeeringManagementClientOperationsMixin\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - }, - "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=None, # type: Optional[str]", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: Optional[str] = None,", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "legacy_peerings": "LegacyPeeringsOperations", - "operations": "Operations", - "peer_asns": "PeerAsnsOperations", - "peering_locations": "PeeringLocationsOperations", - "peerings": "PeeringsOperations", - "peering_service_locations": "PeeringServiceLocationsOperations", - "peering_service_prefixes": "PeeringServicePrefixesOperations", - "prefixes": "PrefixesOperations", - "peering_service_providers": "PeeringServiceProvidersOperations", - "peering_services": "PeeringServicesOperations" - }, - "operation_mixins": { - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"ClientAuthenticationError\", \"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.mgmt.core.exceptions\": [\"ARMErrorFormat\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"Optional\", \"TypeVar\", \"Union\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"ClientAuthenticationError\", \"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.mgmt.core.exceptions\": [\"ARMErrorFormat\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"Optional\", \"TypeVar\", \"Union\"]}}}", - "operations": { - "check_service_provider_availability" : { - "sync": { - "signature": "def check_service_provider_availability(\n self,\n check_service_provider_availability_input, # type: \"_models.CheckServiceProviderAvailabilityInput\"\n **kwargs # type: Any\n):\n", - "doc": "\"\"\"Checks if the peering service provider is present within 1000 miles of customer\u0027s location.\n\n:param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput\n indicating customer location and service provider.\n:type check_service_provider_availability_input: ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: Enum0, or the result of cls(response)\n:rtype: str or ~azure.mgmt.peering.models.Enum0\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" - }, - "async": { - "coroutine": true, - "signature": "async def check_service_provider_availability(\n self,\n check_service_provider_availability_input: \"_models.CheckServiceProviderAvailabilityInput\",\n **kwargs\n) -\u003e Union[str, \"_models.Enum0\"]:\n", - "doc": "\"\"\"Checks if the peering service provider is present within 1000 miles of customer\u0027s location.\n\n:param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput\n indicating customer location and service provider.\n:type check_service_provider_availability_input: ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: Enum0, or the result of cls(response)\n:rtype: str or ~azure.mgmt.peering.models.Enum0\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" - }, - "call": "check_service_provider_availability_input" - } - } - } -} \ No newline at end of file diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_patch.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_peering_management_client.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_peering_management_client.py index 84c4d27846ed..6cbb27568b6f 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_peering_management_client.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_peering_management_client.py @@ -6,119 +6,168 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from ._configuration import PeeringManagementClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + CdnPeeringPrefixesOperations, + ConnectionMonitorTestsOperations, + LegacyPeeringsOperations, + LookingGlassOperations, + Operations, + PeerAsnsOperations, + PeeringLocationsOperations, + PeeringManagementClientOperationsMixin, + PeeringServiceCountriesOperations, + PeeringServiceLocationsOperations, + PeeringServiceProvidersOperations, + PeeringServicesOperations, + PeeringsOperations, + PrefixesOperations, + ReceivedRoutesOperations, + RegisteredAsnsOperations, + RegisteredPrefixesOperations, + RpUnbilledPrefixesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import PeeringManagementClientConfiguration -from .operations import PeeringManagementClientOperationsMixin -from .operations import LegacyPeeringsOperations -from .operations import Operations -from .operations import PeerAsnsOperations -from .operations import PeeringLocationsOperations -from .operations import PeeringsOperations -from .operations import PeeringServiceLocationsOperations -from .operations import PeeringServicePrefixesOperations -from .operations import PrefixesOperations -from .operations import PeeringServiceProvidersOperations -from .operations import PeeringServicesOperations -from . import models -class PeeringManagementClient(PeeringManagementClientOperationsMixin): +class PeeringManagementClient( + PeeringManagementClientOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Peering Client. + :ivar cdn_peering_prefixes: CdnPeeringPrefixesOperations operations + :vartype cdn_peering_prefixes: azure.mgmt.peering.operations.CdnPeeringPrefixesOperations :ivar legacy_peerings: LegacyPeeringsOperations operations :vartype legacy_peerings: azure.mgmt.peering.operations.LegacyPeeringsOperations + :ivar looking_glass: LookingGlassOperations operations + :vartype looking_glass: azure.mgmt.peering.operations.LookingGlassOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.peering.operations.Operations :ivar peer_asns: PeerAsnsOperations operations :vartype peer_asns: azure.mgmt.peering.operations.PeerAsnsOperations :ivar peering_locations: PeeringLocationsOperations operations :vartype peering_locations: azure.mgmt.peering.operations.PeeringLocationsOperations + :ivar registered_asns: RegisteredAsnsOperations operations + :vartype registered_asns: azure.mgmt.peering.operations.RegisteredAsnsOperations + :ivar registered_prefixes: RegisteredPrefixesOperations operations + :vartype registered_prefixes: azure.mgmt.peering.operations.RegisteredPrefixesOperations :ivar peerings: PeeringsOperations operations :vartype peerings: azure.mgmt.peering.operations.PeeringsOperations + :ivar received_routes: ReceivedRoutesOperations operations + :vartype received_routes: azure.mgmt.peering.operations.ReceivedRoutesOperations + :ivar connection_monitor_tests: ConnectionMonitorTestsOperations operations + :vartype connection_monitor_tests: + azure.mgmt.peering.operations.ConnectionMonitorTestsOperations + :ivar peering_service_countries: PeeringServiceCountriesOperations operations + :vartype peering_service_countries: + azure.mgmt.peering.operations.PeeringServiceCountriesOperations :ivar peering_service_locations: PeeringServiceLocationsOperations operations - :vartype peering_service_locations: azure.mgmt.peering.operations.PeeringServiceLocationsOperations - :ivar peering_service_prefixes: PeeringServicePrefixesOperations operations - :vartype peering_service_prefixes: azure.mgmt.peering.operations.PeeringServicePrefixesOperations + :vartype peering_service_locations: + azure.mgmt.peering.operations.PeeringServiceLocationsOperations :ivar prefixes: PrefixesOperations operations :vartype prefixes: azure.mgmt.peering.operations.PrefixesOperations :ivar peering_service_providers: PeeringServiceProvidersOperations operations - :vartype peering_service_providers: azure.mgmt.peering.operations.PeeringServiceProvidersOperations + :vartype peering_service_providers: + azure.mgmt.peering.operations.PeeringServiceProvidersOperations :ivar peering_services: PeeringServicesOperations operations :vartype peering_services: azure.mgmt.peering.operations.PeeringServicesOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar rp_unbilled_prefixes: RpUnbilledPrefixesOperations operations + :vartype rp_unbilled_prefixes: azure.mgmt.peering.operations.RpUnbilledPrefixesOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. + :param subscription_id: The Azure subscription ID. Required. :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 + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, - credential, # type: "TokenCredential" - 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 = PeeringManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = PeeringManagementClientConfiguration( + 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.legacy_peerings = LegacyPeeringsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.peer_asns = PeerAsnsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.cdn_peering_prefixes = CdnPeeringPrefixesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.legacy_peerings = LegacyPeeringsOperations(self._client, self._config, self._serialize, self._deserialize) + self.looking_glass = LookingGlassOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.peer_asns = PeerAsnsOperations(self._client, self._config, self._serialize, self._deserialize) self.peering_locations = PeeringLocationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.peerings = PeeringsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.registered_asns = RegisteredAsnsOperations(self._client, self._config, self._serialize, self._deserialize) + self.registered_prefixes = RegisteredPrefixesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.peerings = PeeringsOperations(self._client, self._config, self._serialize, self._deserialize) + self.received_routes = ReceivedRoutesOperations(self._client, self._config, self._serialize, self._deserialize) + self.connection_monitor_tests = ConnectionMonitorTestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.peering_service_countries = PeeringServiceCountriesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.peering_service_locations = PeeringServiceLocationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.peering_service_prefixes = PeeringServicePrefixesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.prefixes = PrefixesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.prefixes = PrefixesOperations(self._client, self._config, self._serialize, self._deserialize) self.peering_service_providers = PeeringServiceProvidersOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.peering_services = PeeringServicesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.rp_unbilled_prefixes = RpUnbilledPrefixesOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_serialization.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_vendor.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_vendor.py new file mode 100644 index 000000000000..5177ea4b75f9 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_vendor.py @@ -0,0 +1,47 @@ +# -------------------------------------------------------------------------- +# 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 abc import ABC +from typing import TYPE_CHECKING + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import PeeringManagementClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import PipelineClient + + from ._serialization import Deserializer, Serializer + + +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) + + +class PeeringManagementClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: PeeringManagementClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_version.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_version.py index c47f66669f1b..e5754a47ce68 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_version.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/__init__.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/__init__.py index 0a779308d8f0..4887b777dceb 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/__init__.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/__init__.py @@ -7,4 +7,17 @@ # -------------------------------------------------------------------------- from ._peering_management_client import PeeringManagementClient -__all__ = ['PeeringManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PeeringManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_configuration.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_configuration.py index 52b4e0ae8333..29ad32857080 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_configuration.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_configuration.py @@ -6,62 +6,67 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class PeeringManagementClientConfiguration(Configuration): +class PeeringManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for PeeringManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The Azure subscription ID. + :param subscription_id: The Azure subscription ID. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(PeeringManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-10-01") # type: Literal["2022-10-01"] + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(PeeringManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.api_version = "2019-08-01-preview" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-peering/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-peering/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_patch.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_peering_management_client.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_peering_management_client.py index 1d6c6e5e7219..8a4efe8c7103 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_peering_management_client.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_peering_management_client.py @@ -6,115 +6,168 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from .._serialization import Deserializer, Serializer +from ._configuration import PeeringManagementClientConfiguration +from .operations import ( + CdnPeeringPrefixesOperations, + ConnectionMonitorTestsOperations, + LegacyPeeringsOperations, + LookingGlassOperations, + Operations, + PeerAsnsOperations, + PeeringLocationsOperations, + PeeringManagementClientOperationsMixin, + PeeringServiceCountriesOperations, + PeeringServiceLocationsOperations, + PeeringServiceProvidersOperations, + PeeringServicesOperations, + PeeringsOperations, + PrefixesOperations, + ReceivedRoutesOperations, + RegisteredAsnsOperations, + RegisteredPrefixesOperations, + RpUnbilledPrefixesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import PeeringManagementClientConfiguration -from .operations import PeeringManagementClientOperationsMixin -from .operations import LegacyPeeringsOperations -from .operations import Operations -from .operations import PeerAsnsOperations -from .operations import PeeringLocationsOperations -from .operations import PeeringsOperations -from .operations import PeeringServiceLocationsOperations -from .operations import PeeringServicePrefixesOperations -from .operations import PrefixesOperations -from .operations import PeeringServiceProvidersOperations -from .operations import PeeringServicesOperations -from .. import models - -class PeeringManagementClient(PeeringManagementClientOperationsMixin): +class PeeringManagementClient( + PeeringManagementClientOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Peering Client. + :ivar cdn_peering_prefixes: CdnPeeringPrefixesOperations operations + :vartype cdn_peering_prefixes: azure.mgmt.peering.aio.operations.CdnPeeringPrefixesOperations :ivar legacy_peerings: LegacyPeeringsOperations operations :vartype legacy_peerings: azure.mgmt.peering.aio.operations.LegacyPeeringsOperations + :ivar looking_glass: LookingGlassOperations operations + :vartype looking_glass: azure.mgmt.peering.aio.operations.LookingGlassOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.peering.aio.operations.Operations :ivar peer_asns: PeerAsnsOperations operations :vartype peer_asns: azure.mgmt.peering.aio.operations.PeerAsnsOperations :ivar peering_locations: PeeringLocationsOperations operations :vartype peering_locations: azure.mgmt.peering.aio.operations.PeeringLocationsOperations + :ivar registered_asns: RegisteredAsnsOperations operations + :vartype registered_asns: azure.mgmt.peering.aio.operations.RegisteredAsnsOperations + :ivar registered_prefixes: RegisteredPrefixesOperations operations + :vartype registered_prefixes: azure.mgmt.peering.aio.operations.RegisteredPrefixesOperations :ivar peerings: PeeringsOperations operations :vartype peerings: azure.mgmt.peering.aio.operations.PeeringsOperations + :ivar received_routes: ReceivedRoutesOperations operations + :vartype received_routes: azure.mgmt.peering.aio.operations.ReceivedRoutesOperations + :ivar connection_monitor_tests: ConnectionMonitorTestsOperations operations + :vartype connection_monitor_tests: + azure.mgmt.peering.aio.operations.ConnectionMonitorTestsOperations + :ivar peering_service_countries: PeeringServiceCountriesOperations operations + :vartype peering_service_countries: + azure.mgmt.peering.aio.operations.PeeringServiceCountriesOperations :ivar peering_service_locations: PeeringServiceLocationsOperations operations - :vartype peering_service_locations: azure.mgmt.peering.aio.operations.PeeringServiceLocationsOperations - :ivar peering_service_prefixes: PeeringServicePrefixesOperations operations - :vartype peering_service_prefixes: azure.mgmt.peering.aio.operations.PeeringServicePrefixesOperations + :vartype peering_service_locations: + azure.mgmt.peering.aio.operations.PeeringServiceLocationsOperations :ivar prefixes: PrefixesOperations operations :vartype prefixes: azure.mgmt.peering.aio.operations.PrefixesOperations :ivar peering_service_providers: PeeringServiceProvidersOperations operations - :vartype peering_service_providers: azure.mgmt.peering.aio.operations.PeeringServiceProvidersOperations + :vartype peering_service_providers: + azure.mgmt.peering.aio.operations.PeeringServiceProvidersOperations :ivar peering_services: PeeringServicesOperations operations :vartype peering_services: azure.mgmt.peering.aio.operations.PeeringServicesOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar rp_unbilled_prefixes: RpUnbilledPrefixesOperations operations + :vartype rp_unbilled_prefixes: azure.mgmt.peering.aio.operations.RpUnbilledPrefixesOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The Azure subscription ID. + :param subscription_id: The Azure subscription ID. Required. :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 + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( self, credential: "AsyncTokenCredential", 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 = PeeringManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = PeeringManagementClientConfiguration( + 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.legacy_peerings = LegacyPeeringsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.peer_asns = PeerAsnsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.cdn_peering_prefixes = CdnPeeringPrefixesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.legacy_peerings = LegacyPeeringsOperations(self._client, self._config, self._serialize, self._deserialize) + self.looking_glass = LookingGlassOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.peer_asns = PeerAsnsOperations(self._client, self._config, self._serialize, self._deserialize) self.peering_locations = PeeringLocationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.peerings = PeeringsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.registered_asns = RegisteredAsnsOperations(self._client, self._config, self._serialize, self._deserialize) + self.registered_prefixes = RegisteredPrefixesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.peerings = PeeringsOperations(self._client, self._config, self._serialize, self._deserialize) + self.received_routes = ReceivedRoutesOperations(self._client, self._config, self._serialize, self._deserialize) + self.connection_monitor_tests = ConnectionMonitorTestsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.peering_service_countries = PeeringServiceCountriesOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.peering_service_locations = PeeringServiceLocationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.peering_service_prefixes = PeeringServicePrefixesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.prefixes = PrefixesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.prefixes = PrefixesOperations(self._client, self._config, self._serialize, self._deserialize) self.peering_service_providers = PeeringServiceProvidersOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.peering_services = PeeringServicesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.rp_unbilled_prefixes = RpUnbilledPrefixesOperations( + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_vendor.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_vendor.py new file mode 100644 index 000000000000..969390d27547 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/_vendor.py @@ -0,0 +1,28 @@ +# -------------------------------------------------------------------------- +# 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 abc import ABC +from typing import TYPE_CHECKING + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import PeeringManagementClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import AsyncPipelineClient + + from .._serialization import Deserializer, Serializer + + +class PeeringManagementClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: PeeringManagementClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/__init__.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/__init__.py index 2c62d44850a9..3a7f6307d71e 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/__init__.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/__init__.py @@ -6,28 +6,48 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from ._cdn_peering_prefixes_operations import CdnPeeringPrefixesOperations from ._peering_management_client_operations import PeeringManagementClientOperationsMixin from ._legacy_peerings_operations import LegacyPeeringsOperations +from ._looking_glass_operations import LookingGlassOperations from ._operations import Operations from ._peer_asns_operations import PeerAsnsOperations from ._peering_locations_operations import PeeringLocationsOperations +from ._registered_asns_operations import RegisteredAsnsOperations +from ._registered_prefixes_operations import RegisteredPrefixesOperations from ._peerings_operations import PeeringsOperations +from ._received_routes_operations import ReceivedRoutesOperations +from ._connection_monitor_tests_operations import ConnectionMonitorTestsOperations +from ._peering_service_countries_operations import PeeringServiceCountriesOperations from ._peering_service_locations_operations import PeeringServiceLocationsOperations -from ._peering_service_prefixes_operations import PeeringServicePrefixesOperations from ._prefixes_operations import PrefixesOperations from ._peering_service_providers_operations import PeeringServiceProvidersOperations from ._peering_services_operations import PeeringServicesOperations +from ._rp_unbilled_prefixes_operations import RpUnbilledPrefixesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'PeeringManagementClientOperationsMixin', - 'LegacyPeeringsOperations', - 'Operations', - 'PeerAsnsOperations', - 'PeeringLocationsOperations', - 'PeeringsOperations', - 'PeeringServiceLocationsOperations', - 'PeeringServicePrefixesOperations', - 'PrefixesOperations', - 'PeeringServiceProvidersOperations', - 'PeeringServicesOperations', + "CdnPeeringPrefixesOperations", + "PeeringManagementClientOperationsMixin", + "LegacyPeeringsOperations", + "LookingGlassOperations", + "Operations", + "PeerAsnsOperations", + "PeeringLocationsOperations", + "RegisteredAsnsOperations", + "RegisteredPrefixesOperations", + "PeeringsOperations", + "ReceivedRoutesOperations", + "ConnectionMonitorTestsOperations", + "PeeringServiceCountriesOperations", + "PeeringServiceLocationsOperations", + "PrefixesOperations", + "PeeringServiceProvidersOperations", + "PeeringServicesOperations", + "RpUnbilledPrefixesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_cdn_peering_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_cdn_peering_prefixes_operations.py new file mode 100644 index 000000000000..c5fb1e8b3919 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_cdn_peering_prefixes_operations.py @@ -0,0 +1,144 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._cdn_peering_prefixes_operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CdnPeeringPrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`cdn_peering_prefixes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, peering_location: str, **kwargs: Any) -> AsyncIterable["_models.CdnPeeringPrefix"]: + """Lists all of the advertised prefixes for the specified peering location. + + :param peering_location: The peering location. Required. + :type peering_location: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either CdnPeeringPrefix or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.CdnPeeringPrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnPeeringPrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + peering_location=peering_location, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("CdnPeeringPrefixListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/cdnPeeringPrefixes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_connection_monitor_tests_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_connection_monitor_tests_operations.py new file mode 100644 index 000000000000..ed4f248abe32 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_connection_monitor_tests_operations.py @@ -0,0 +1,446 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._connection_monitor_tests_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_peering_service_request, +) +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ConnectionMonitorTestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`connection_monitor_tests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, peering_service_name: str, connection_monitor_test_name: str, **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Gets an existing connection monitor test with the specified name under the given subscription, + resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConnectionMonitorTest] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + connection_monitor_test_name=connection_monitor_test_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ConnectionMonitorTest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}"} # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + connection_monitor_test: _models.ConnectionMonitorTest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Creates or updates a connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :param connection_monitor_test: The properties needed to create a connection monitor test. + Required. + :type connection_monitor_test: ~azure.mgmt.peering.models.ConnectionMonitorTest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + connection_monitor_test: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Creates or updates a connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :param connection_monitor_test: The properties needed to create a connection monitor test. + Required. + :type connection_monitor_test: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + connection_monitor_test: Union[_models.ConnectionMonitorTest, IO], + **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Creates or updates a connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :param connection_monitor_test: The properties needed to create a connection monitor test. Is + either a model type or a IO type. Required. + :type connection_monitor_test: ~azure.mgmt.peering.models.ConnectionMonitorTest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConnectionMonitorTest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(connection_monitor_test, (IO, bytes)): + _content = connection_monitor_test + else: + _json = self._serialize.body(connection_monitor_test, "ConnectionMonitorTest") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + connection_monitor_test_name=connection_monitor_test_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ConnectionMonitorTest", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ConnectionMonitorTest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_service_name: str, connection_monitor_test_name: str, **kwargs: Any + ) -> None: + """Deletes an existing connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + connection_monitor_test_name=connection_monitor_test_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}"} # type: ignore + + @distributed_trace + def list_by_peering_service( + self, resource_group_name: str, peering_service_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ConnectionMonitorTest"]: + """Lists all connection monitor tests under the given subscription, resource group and peering + service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConnectionMonitorTest or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.ConnectionMonitorTest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConnectionMonitorTestListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_service_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_peering_service.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ConnectionMonitorTestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_peering_service.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_legacy_peerings_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_legacy_peerings_operations.py index c11197e94e75..90748c93ece5 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_legacy_peerings_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_legacy_peerings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,137 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._legacy_peerings_operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class LegacyPeeringsOperations: - """LegacyPeeringsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class LegacyPeeringsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`legacy_peerings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( self, peering_location: str, - kind: Union[str, "_models.Enum1"], - **kwargs - ) -> AsyncIterable["_models.PeeringListResult"]: + kind: Union[str, _models.LegacyPeeringsKind], + asn: Optional[int] = None, + direct_peering_type: Optional[Union[str, _models.DirectPeeringType]] = None, + **kwargs: Any + ) -> AsyncIterable["_models.Peering"]: """Lists all of the legacy peerings under the given subscription matching the specified kind and location. - :param peering_location: The location of the peering. + :param peering_location: The location of the peering. Required. :type peering_location: str - :param kind: The kind of the peering. - :type kind: str or ~azure.mgmt.peering.models.Enum1 + :param kind: The kind of the peering. Known values are: "Direct" and "Exchange". Required. + :type kind: str or ~azure.mgmt.peering.models.LegacyPeeringsKind + :param asn: The ASN number associated with a legacy peering. Default value is None. + :type asn: int + :param direct_peering_type: The direct peering type. Known values are: "Edge", "Transit", + "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". Default value is None. + :type direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Peering or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.Peering] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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['peeringLocation'] = self._serialize.query("peering_location", peering_location, 'str') - query_parameters['kind'] = self._serialize.query("kind", kind, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + peering_location=peering_location, + kind=kind, + asn=asn, + direct_peering_type=direct_peering_type, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringListResult', pipeline_response) + deserialized = self._deserialize("PeeringListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -102,17 +145,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/legacyPeerings'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/legacyPeerings"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_looking_glass_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_looking_glass_operations.py new file mode 100644 index 000000000000..6055fbcaa7ef --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_looking_glass_operations.py @@ -0,0 +1,133 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._looking_glass_operations import build_invoke_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class LookingGlassOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`looking_glass` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def invoke( + self, + command: Union[str, _models.LookingGlassCommand], + source_type: Union[str, _models.LookingGlassSourceType], + source_location: str, + destination_ip: str, + **kwargs: Any + ) -> _models.LookingGlassOutput: + """Run looking glass functionality. + + :param command: The command to be executed: ping, traceroute, bgpRoute. Known values are: + "Traceroute", "Ping", and "BgpRoute". Required. + :type command: str or ~azure.mgmt.peering.models.LookingGlassCommand + :param source_type: The type of the source: Edge site or Azure Region. Known values are: + "EdgeSite" and "AzureRegion". Required. + :type source_type: str or ~azure.mgmt.peering.models.LookingGlassSourceType + :param source_location: The location of the source. Required. + :type source_location: str + :param destination_ip: The IP address of the destination. Required. + :type destination_ip: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: LookingGlassOutput or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.LookingGlassOutput + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LookingGlassOutput] + + request = build_invoke_request( + subscription_id=self._config.subscription_id, + command=command, + source_type=source_type, + source_location=source_location, + destination_ip=destination_ip, + api_version=api_version, + template_url=self.invoke.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("LookingGlassOutput", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + invoke.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/lookingGlass"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_operations.py index 5d790b1b2369..b2022d4a4a15 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,115 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs - ) -> AsyncIterable["_models.OperationListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available API operations for peering resources. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +123,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Peering/operations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Peering/operations"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_patch.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peer_asns_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peer_asns_operations.py index 5f994e2648d4..bee36e9ec7ed 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peer_asns_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peer_asns_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,261 +6,356 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._peer_asns_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_subscription_request, +) +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PeerAsnsOperations: - """PeerAsnsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PeerAsnsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`peer_asns` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - async def get( - self, - peer_asn_name: str, - **kwargs - ) -> "_models.PeerAsn": + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, peer_asn_name: str, **kwargs: Any) -> _models.PeerAsn: """Gets the peer ASN with the specified name under the given subscription. - :param peer_asn_name: The peer ASN name. + :param peer_asn_name: The peer ASN name. Required. :type peer_asn_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeerAsn, or the result of cls(response) + :return: PeerAsn or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeerAsn - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeerAsn"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'peerAsnName': self._serialize.url("peer_asn_name", peer_asn_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeerAsn] + + request = build_get_request( + peer_asn_name=peer_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PeerAsn', pipeline_response) + deserialized = self._deserialize("PeerAsn", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}"} # type: ignore + + @overload async def create_or_update( - self, - peer_asn_name: str, - peer_asn: "_models.PeerAsn", - **kwargs - ) -> "_models.PeerAsn": + self, peer_asn_name: str, peer_asn: _models.PeerAsn, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PeerAsn: """Creates a new peer ASN or updates an existing peer ASN with the specified name under the given subscription. - :param peer_asn_name: The peer ASN name. + :param peer_asn_name: The peer ASN name. Required. :type peer_asn_name: str - :param peer_asn: The peer ASN. + :param peer_asn: The peer ASN. Required. :type peer_asn: ~azure.mgmt.peering.models.PeerAsn + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeerAsn, or the result of cls(response) + :return: PeerAsn or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeerAsn - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, peer_asn_name: str, peer_asn: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PeerAsn: + """Creates a new peer ASN or updates an existing peer ASN with the specified name under the given + subscription. + + :param peer_asn_name: The peer ASN name. Required. + :type peer_asn_name: str + :param peer_asn: The peer ASN. Required. + :type peer_asn: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeerAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeerAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, peer_asn_name: str, peer_asn: Union[_models.PeerAsn, IO], **kwargs: Any + ) -> _models.PeerAsn: + """Creates a new peer ASN or updates an existing peer ASN with the specified name under the given + subscription. + + :param peer_asn_name: The peer ASN name. Required. + :type peer_asn_name: str + :param peer_asn: The peer ASN. Is either a model type or a IO type. Required. + :type peer_asn: ~azure.mgmt.peering.models.PeerAsn or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeerAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeerAsn + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeerAsn"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'peerAsnName': self._serialize.url("peer_asn_name", peer_asn_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peer_asn, 'PeerAsn') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeerAsn] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peer_asn, (IO, bytes)): + _content = peer_asn + else: + _json = self._serialize.body(peer_asn, "PeerAsn") + + request = build_create_or_update_request( + peer_asn_name=peer_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PeerAsn', pipeline_response) + deserialized = self._deserialize("PeerAsn", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('PeerAsn', pipeline_response) + deserialized = self._deserialize("PeerAsn", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}'} # type: ignore - async def delete( - self, - peer_asn_name: str, - **kwargs - ) -> None: + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}"} # type: ignore + + @distributed_trace_async + async def delete(self, peer_asn_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Deletes an existing peer ASN with the specified name under the given subscription. - :param peer_asn_name: The peer ASN name. + :param peer_asn_name: The peer ASN name. Required. :type peer_asn_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'peerAsnName': self._serialize.url("peer_asn_name", peer_asn_name, 'str'), - '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') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + peer_asn_name=peer_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}'} # type: ignore + delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}"} # type: ignore - def list_by_subscription( - self, - **kwargs - ) -> AsyncIterable["_models.PeerAsnListResult"]: + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.PeerAsn"]: """Lists all of the peer ASNs under the given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeerAsnListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeerAsnListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeerAsn or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeerAsn] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeerAsnListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeerAsnListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_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, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeerAsnListResult', pipeline_response) + deserialized = self._deserialize("PeerAsnListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -268,17 +364,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_locations_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_locations_operations.py index f58059bf6026..c4da3e7e4065 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_locations_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_locations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,128 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._peering_locations_operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PeeringLocationsOperations: - """PeeringLocationsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PeeringLocationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`peering_locations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( self, - kind: Union[str, "_models.Enum14"], - direct_peering_type: Optional[Union[str, "_models.Enum15"]] = None, - **kwargs - ) -> AsyncIterable["_models.PeeringLocationListResult"]: + kind: Union[str, _models.PeeringLocationsKind], + direct_peering_type: Optional[Union[str, _models.PeeringLocationsDirectPeeringType]] = None, + **kwargs: Any + ) -> AsyncIterable["_models.PeeringLocation"]: """Lists all of the available peering locations for the specified kind of peering. - :param kind: The kind of the peering. - :type kind: str or ~azure.mgmt.peering.models.Enum14 - :param direct_peering_type: The type of direct peering. - :type direct_peering_type: str or ~azure.mgmt.peering.models.Enum15 + :param kind: The kind of the peering. Known values are: "Direct" and "Exchange". Required. + :type kind: str or ~azure.mgmt.peering.models.PeeringLocationsKind + :param direct_peering_type: The type of direct peering. Known values are: "Edge", "Transit", + "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". Default value is None. + :type direct_peering_type: str or ~azure.mgmt.peering.models.PeeringLocationsDirectPeeringType :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringLocationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringLocationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringLocation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringLocation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringLocationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringLocationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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['kind'] = self._serialize.query("kind", kind, 'str') - if direct_peering_type is not None: - query_parameters['directPeeringType'] = self._serialize.query("direct_peering_type", direct_peering_type, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + kind=kind, + direct_peering_type=direct_peering_type, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringLocationListResult', pipeline_response) + deserialized = self._deserialize("PeeringLocationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -102,17 +136,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringLocations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringLocations"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_management_client_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_management_client_operations.py index 1add2531d0f3..45f08e3d4752 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_management_client_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_management_client_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,77 +6,156 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._peering_management_client_operations import build_check_service_provider_availability_request +from .._vendor import PeeringManagementClientMixinABC -T = TypeVar('T') +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PeeringManagementClientOperationsMixin: +class PeeringManagementClientOperationsMixin(PeeringManagementClientMixinABC): + @overload async def check_service_provider_availability( self, - check_service_provider_availability_input: "_models.CheckServiceProviderAvailabilityInput", - **kwargs - ) -> Union[str, "_models.Enum0"]: + check_service_provider_availability_input: _models.CheckServiceProviderAvailabilityInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Union[str, _models.Enum0]: """Checks if the peering service provider is present within 1000 miles of customer's location. :param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput - indicating customer location and service provider. - :type check_service_provider_availability_input: ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput + indicating customer location and service provider. Required. + :type check_service_provider_availability_input: + ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Enum0, or the result of cls(response) + :return: Enum0 or the result of cls(response) :rtype: str or ~azure.mgmt.peering.models.Enum0 - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_service_provider_availability( + self, check_service_provider_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> Union[str, _models.Enum0]: + """Checks if the peering service provider is present within 1000 miles of customer's location. + + :param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput + indicating customer location and service provider. Required. + :type check_service_provider_availability_input: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Enum0 or the result of cls(response) + :rtype: str or ~azure.mgmt.peering.models.Enum0 + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_service_provider_availability( + self, + check_service_provider_availability_input: Union[_models.CheckServiceProviderAvailabilityInput, IO], + **kwargs: Any + ) -> Union[str, _models.Enum0]: + """Checks if the peering service provider is present within 1000 miles of customer's location. + + :param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput + indicating customer location and service provider. Is either a model type or a IO type. + Required. + :type check_service_provider_availability_input: + ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Enum0 or the result of cls(response) + :rtype: str or ~azure.mgmt.peering.models.Enum0 + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Union[str, "_models.Enum0"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.check_service_provider_availability.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(check_service_provider_availability_input, 'CheckServiceProviderAvailabilityInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Union[str, _models.Enum0]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(check_service_provider_availability_input, (IO, bytes)): + _content = check_service_provider_availability_input + else: + _json = self._serialize.body( + check_service_provider_availability_input, "CheckServiceProviderAvailabilityInput" + ) + + request = build_check_service_provider_availability_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_service_provider_availability.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('str', pipeline_response) + deserialized = self._deserialize("str", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_service_provider_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/CheckServiceProviderAvailability'} # type: ignore + + check_service_provider_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/checkServiceProviderAvailability"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_countries_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_countries_operations.py new file mode 100644 index 000000000000..dbca4f1757d2 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_countries_operations.py @@ -0,0 +1,143 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._peering_service_countries_operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PeeringServiceCountriesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`peering_service_countries` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.PeeringServiceCountry"]: + """Lists all of the available countries for peering service. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringServiceCountry or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServiceCountry] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceCountryListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringServiceCountryListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceCountries"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_locations_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_locations_operations.py index a255a7df841b..195716047020 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_locations_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_locations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,86 +6,122 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._peering_service_locations_operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PeeringServiceLocationsOperations: - """PeeringServiceLocationsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PeeringServiceLocationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`peering_service_locations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs - ) -> AsyncIterable["_models.PeeringServiceLocationListResult"]: - """Lists all of the available peering service locations for the specified kind of peering. + @distributed_trace + def list(self, country: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.PeeringServiceLocation"]: + """Lists all of the available locations for peering service. + :param country: The country of interest, in which the locations are to be present. Default + value is None. + :type country: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceLocationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServiceLocationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringServiceLocation or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServiceLocation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceLocationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceLocationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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_request( + subscription_id=self._config.subscription_id, + country=country, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceLocationListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceLocationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -93,17 +130,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceLocations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceLocations"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_prefixes_operations.py deleted file mode 100644 index 08f17fd13de1..000000000000 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_prefixes_operations.py +++ /dev/null @@ -1,239 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models - -T = TypeVar('T') -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - -class PeeringServicePrefixesOperations: - """PeeringServicePrefixesOperations async operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - """ - - models = _models - - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - async def get( - self, - resource_group_name: str, - peering_service_name: str, - prefix_name: str, - **kwargs - ) -> "_models.PeeringServicePrefix": - """Gets the peering service prefix. - - :param resource_group_name: The resource group name. - :type resource_group_name: str - :param peering_service_name: The peering service name. - :type peering_service_name: str - :param prefix_name: The prefix name. - :type prefix_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringServicePrefix, or the result of cls(response) - :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefix"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), - '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] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore - - async def create_or_update( - self, - resource_group_name: str, - peering_service_name: str, - prefix_name: str, - peering_service_prefix: "_models.PeeringServicePrefix", - **kwargs - ) -> "_models.PeeringServicePrefix": - """Creates or updates the peering prefix. - - :param resource_group_name: The resource group name. - :type resource_group_name: str - :param peering_service_name: The peering service name. - :type peering_service_name: str - :param prefix_name: The prefix name. - :type prefix_name: str - :param peering_service_prefix: The IP prefix for an peering. - :type peering_service_prefix: ~azure.mgmt.peering.models.PeeringServicePrefix - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringServicePrefix, or the result of cls(response) - :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefix"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), - '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] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peering_service_prefix, 'PeeringServicePrefix') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore - - async def delete( - self, - resource_group_name: str, - peering_service_name: str, - prefix_name: str, - **kwargs - ) -> None: - """removes the peering prefix. - - :param resource_group_name: The resource group name. - :type resource_group_name: str - :param peering_service_name: The peering service name. - :type peering_service_name: str - :param prefix_name: The prefix name. - :type prefix_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), - '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] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_providers_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_providers_operations.py index a3a9238db4ce..d019aa90c885 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_providers_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_service_providers_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,86 +6,118 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._peering_service_providers_operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PeeringServiceProvidersOperations: - """PeeringServiceProvidersOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PeeringServiceProvidersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`peering_service_providers` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs - ) -> AsyncIterable["_models.PeeringServiceProviderListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.PeeringServiceProvider"]: """Lists all of the available peering service locations for the specified kind of peering. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceProviderListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServiceProviderListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringServiceProvider or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServiceProvider] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceProviderListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceProviderListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceProviderListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceProviderListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -93,17 +126,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceProviders'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceProviders"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_services_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_services_operations.py index ccd6b47b11b7..2c38500ae284 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_services_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peering_services_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,347 +6,535 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._peering_services_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_initialize_connection_monitor_request, + build_list_by_resource_group_request, + build_list_by_subscription_request, + build_update_request, +) +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PeeringServicesOperations: - """PeeringServicesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PeeringServicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`peering_services` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get( - self, - resource_group_name: str, - peering_service_name: str, - **kwargs - ) -> "_models.PeeringService": + @distributed_trace_async + async def get(self, resource_group_name: str, peering_service_name: str, **kwargs: Any) -> _models.PeeringService: """Gets an existing peering service with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering. + :param peering_service_name: The name of the peering. Required. :type peering_service_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringService, or the result of cls(response) + :return: PeeringService or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringService - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringService"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringService] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + + @overload async def create_or_update( self, resource_group_name: str, peering_service_name: str, - peering_service: "_models.PeeringService", - **kwargs - ) -> "_models.PeeringService": + peering_service: _models.PeeringService, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: """Creates a new peering service or updates an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering service. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str - :param peering_service: The properties needed to create or update a peering service. + :param peering_service: The properties needed to create or update a peering service. Required. :type peering_service: ~azure.mgmt.peering.models.PeeringService + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + peering_service: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: + """Creates a new peering service or updates an existing peering with the specified name under the + given subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param peering_service: The properties needed to create or update a peering service. Required. + :type peering_service: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + peering_service: Union[_models.PeeringService, IO], + **kwargs: Any + ) -> _models.PeeringService: + """Creates a new peering service or updates an existing peering with the specified name under the + given subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param peering_service: The properties needed to create or update a peering service. Is either + a model type or a IO type. Required. + :type peering_service: ~azure.mgmt.peering.models.PeeringService or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringService, or the result of cls(response) + :return: PeeringService or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringService - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringService"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peering_service, 'PeeringService') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringService] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peering_service, (IO, bytes)): + _content = peering_service + else: + _json = self._serialize.body(peering_service, "PeeringService") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore - async def delete( - self, - resource_group_name: str, - peering_service_name: str, - **kwargs + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_service_name: str, **kwargs: Any ) -> None: """Deletes an existing peering service with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering service. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + @overload async def update( self, resource_group_name: str, peering_service_name: str, - tags: "_models.ResourceTags", - **kwargs - ) -> "_models.PeeringService": + tags: _models.ResourceTags, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: """Updates tags for a peering service with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering service. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str - :param tags: The resource tags. + :param tags: The resource tags. Required. :type tags: ~azure.mgmt.peering.models.ResourceTags + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + peering_service_name: str, + tags: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: + """Updates tags for a peering service with the specified name under the given subscription and + resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param tags: The resource tags. Required. + :type tags: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringService, or the result of cls(response) + :return: PeeringService or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringService - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, resource_group_name: str, peering_service_name: str, tags: Union[_models.ResourceTags, IO], **kwargs: Any + ) -> _models.PeeringService: + """Updates tags for a peering service with the specified name under the given subscription and + resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param tags: The resource tags. Is either a model type or a IO type. Required. + :type tags: ~azure.mgmt.peering.models.ResourceTags or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringService"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(tags, 'ResourceTags') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringService] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(tags, (IO, bytes)): + _content = tags + else: + _json = self._serialize.body(tags, "ResourceTags") + + request = build_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + + @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs - ) -> AsyncIterable["_models.PeeringServiceListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PeeringService"]: """Lists all of the peering services under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringService or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringService] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - '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_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -354,65 +543,80 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list_by_subscription( - self, - **kwargs - ) -> AsyncIterable["_models.PeeringServiceListResult"]: + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices"} # type: ignore + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.PeeringService"]: """Lists all of the peerings under the given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringService or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringService] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_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, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -421,17 +625,71 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data + return AsyncItemPaged(get_next, extract_data) + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServices"} # type: ignore + + @distributed_trace_async + async def initialize_connection_monitor( # pylint: disable=inconsistent-return-statements + self, **kwargs: Any + ) -> None: + """Initialize Peering Service for Connection Monitor functionality. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_initialize_connection_monitor_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.initialize_connection_monitor.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServices'} # type: ignore + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + initialize_connection_monitor.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/initializeConnectionMonitor"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peerings_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peerings_operations.py index cd3e27869ae6..a71b7460d495 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peerings_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_peerings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,347 +6,528 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._peerings_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_by_subscription_request, + build_update_request, +) +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PeeringsOperations: - """PeeringsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PeeringsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`peerings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get( - self, - resource_group_name: str, - peering_name: str, - **kwargs - ) -> "_models.Peering": + @distributed_trace_async + async def get(self, resource_group_name: str, peering_name: str, **kwargs: Any) -> _models.Peering: """Gets an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Peering, or the result of cls(response) + :return: Peering or the result of cls(response) :rtype: ~azure.mgmt.peering.models.Peering - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Peering"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Peering] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + + @overload async def create_or_update( self, resource_group_name: str, peering_name: str, - peering: "_models.Peering", - **kwargs - ) -> "_models.Peering": + peering: _models.Peering, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: """Creates a new peering or updates an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str - :param peering: The properties needed to create or update a peering. + :param peering: The properties needed to create or update a peering. Required. :type peering: ~azure.mgmt.peering.models.Peering + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Peering, or the result of cls(response) + :return: Peering or the result of cls(response) :rtype: ~azure.mgmt.peering.models.Peering - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_name: str, + peering: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: + """Creates a new peering or updates an existing peering with the specified name under the given + subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param peering: The properties needed to create or update a peering. Required. + :type peering: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, resource_group_name: str, peering_name: str, peering: Union[_models.Peering, IO], **kwargs: Any + ) -> _models.Peering: + """Creates a new peering or updates an existing peering with the specified name under the given + subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param peering: The properties needed to create or update a peering. Is either a model type or + a IO type. Required. + :type peering: ~azure.mgmt.peering.models.Peering or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Peering"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peering, 'Peering') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Peering] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peering, (IO, bytes)): + _content = peering + else: + _json = self._serialize.body(peering, "Peering") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore - async def delete( - self, - resource_group_name: str, - peering_name: str, - **kwargs + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_name: str, **kwargs: Any ) -> None: """Deletes an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + @overload async def update( self, resource_group_name: str, peering_name: str, - tags: "_models.ResourceTags", - **kwargs - ) -> "_models.Peering": + tags: _models.ResourceTags, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: """Updates tags for a peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str - :param tags: The resource tags. + :param tags: The resource tags. Required. :type tags: ~azure.mgmt.peering.models.ResourceTags + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + peering_name: str, + tags: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: + """Updates tags for a peering with the specified name under the given subscription and resource + group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param tags: The resource tags. Required. + :type tags: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, resource_group_name: str, peering_name: str, tags: Union[_models.ResourceTags, IO], **kwargs: Any + ) -> _models.Peering: + """Updates tags for a peering with the specified name under the given subscription and resource + group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param tags: The resource tags. Is either a model type or a IO type. Required. + :type tags: ~azure.mgmt.peering.models.ResourceTags or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Peering, or the result of cls(response) + :return: Peering or the result of cls(response) :rtype: ~azure.mgmt.peering.models.Peering - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Peering"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - '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] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(tags, 'ResourceTags') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Peering] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(tags, (IO, bytes)): + _content = tags + else: + _json = self._serialize.body(tags, "ResourceTags") + + request = build_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs - ) -> AsyncIterable["_models.PeeringListResult"]: + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Peering"]: """Lists all of the peerings under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Peering or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.Peering] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - '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_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringListResult', pipeline_response) + deserialized = self._deserialize("PeeringListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -354,65 +536,80 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list_by_subscription( - self, - **kwargs - ) -> AsyncIterable["_models.PeeringListResult"]: + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings"} # type: ignore + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Peering"]: """Lists all of the peerings under the given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Peering or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.Peering] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_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, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringListResult', pipeline_response) + deserialized = self._deserialize("PeeringListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -421,17 +618,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerings'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerings"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_prefixes_operations.py index d12f1b574770..1ca05642f1a6 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_prefixes_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_prefixes_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,94 +6,429 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._prefixes_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_peering_service_request, +) +from .._vendor import PeeringManagementClientMixinABC -T = TypeVar('T') +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrefixesOperations: - """PrefixesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`prefixes` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list_by_peering_service( + @distributed_trace_async + async def get( self, resource_group_name: str, peering_service_name: str, - **kwargs - ) -> AsyncIterable["_models.PeeringServicePrefixListResult"]: - """Lists the peerings prefix in the resource group. + prefix_name: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Gets an existing prefix with the specified name under the given subscription, resource group + and peering service. - :param resource_group_name: The resource group name. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The peering service name. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param expand: The properties to be expanded. Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServicePrefixListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServicePrefixListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefixListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServicePrefix] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + prefix_name=prefix_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringServicePrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}"} # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + peering_service_prefix: _models.PeeringServicePrefix, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Creates a new prefix with the specified name under the given subscription, resource group and + peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param peering_service_prefix: The properties needed to create a prefix. Required. + :type peering_service_prefix: ~azure.mgmt.peering.models.PeeringServicePrefix + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + peering_service_prefix: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Creates a new prefix with the specified name under the given subscription, resource group and + peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param peering_service_prefix: The properties needed to create a prefix. Required. + :type peering_service_prefix: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + peering_service_prefix: Union[_models.PeeringServicePrefix, IO], + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Creates a new prefix with the specified name under the given subscription, resource group and + peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param peering_service_prefix: The properties needed to create a prefix. Is either a model type + or a IO type. Required. + :type peering_service_prefix: ~azure.mgmt.peering.models.PeeringServicePrefix or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServicePrefix] + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peering_service_prefix, (IO, bytes)): + _content = peering_service_prefix + else: + _json = self._serialize.body(peering_service_prefix, "PeeringServicePrefix") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + prefix_name=prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PeeringServicePrefix", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PeeringServicePrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_service_name: str, prefix_name: str, **kwargs: Any + ) -> None: + """Deletes an existing prefix with the specified name under the given subscription, resource group + and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + prefix_name=prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}"} # type: ignore + + @distributed_trace + def list_by_peering_service( + self, resource_group_name: str, peering_service_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.PeeringServicePrefix"]: + """Lists all prefixes under the given subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param expand: The properties to be expanded. Default value is None. + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringServicePrefix or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringServicePrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServicePrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): if not next_link: - # Construct URL - url = self.list_by_peering_service.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - '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_peering_service_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + template_url=self.list_by_peering_service.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServicePrefixListResult', pipeline_response) + deserialized = self._deserialize("PeeringServicePrefixListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,17 +437,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_peering_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_peering_service.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_received_routes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_received_routes_operations.py new file mode 100644 index 000000000000..8e60064e3871 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_received_routes_operations.py @@ -0,0 +1,180 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._received_routes_operations import build_list_by_peering_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ReceivedRoutesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`received_routes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_peering( + self, + resource_group_name: str, + peering_name: str, + prefix: Optional[str] = None, + as_path: Optional[str] = None, + origin_as_validation_state: Optional[str] = None, + rpki_validation_state: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.PeeringReceivedRoute"]: + """Lists the prefixes received over the specified peering under the given subscription and + resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param prefix: The optional prefix that can be used to filter the routes. Default value is + None. + :type prefix: str + :param as_path: The optional AS path that can be used to filter the routes. Default value is + None. + :type as_path: str + :param origin_as_validation_state: The optional origin AS validation state that can be used to + filter the routes. Default value is None. + :type origin_as_validation_state: str + :param rpki_validation_state: The optional RPKI validation state that can be used to filter the + routes. Default value is None. + :type rpki_validation_state: str + :param skip_token: The optional page continuation token that is used in the event of paginated + result. Default value is None. + :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 PeeringReceivedRoute or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringReceivedRoute] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringReceivedRouteListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + prefix=prefix, + as_path=as_path, + origin_as_validation_state=origin_as_validation_state, + rpki_validation_state=rpki_validation_state, + skip_token=skip_token, + api_version=api_version, + template_url=self.list_by_peering.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringReceivedRouteListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_peering.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/receivedRoutes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_registered_asns_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_registered_asns_operations.py new file mode 100644 index 000000000000..c06e4dee0001 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_registered_asns_operations.py @@ -0,0 +1,443 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._registered_asns_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_peering_request, +) +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RegisteredAsnsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`registered_asns` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, peering_name: str, registered_asn_name: str, **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Gets an existing registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the registered ASN. Required. + :type registered_asn_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredAsn] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_asn_name=registered_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringRegisteredAsn", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}"} # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_asn_name: str, + registered_asn: _models.PeeringRegisteredAsn, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Creates a new registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the ASN. Required. + :type registered_asn_name: str + :param registered_asn: The properties needed to create a registered ASN. Required. + :type registered_asn: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_asn_name: str, + registered_asn: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Creates a new registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the ASN. Required. + :type registered_asn_name: str + :param registered_asn: The properties needed to create a registered ASN. Required. + :type registered_asn: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_asn_name: str, + registered_asn: Union[_models.PeeringRegisteredAsn, IO], + **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Creates a new registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the ASN. Required. + :type registered_asn_name: str + :param registered_asn: The properties needed to create a registered ASN. Is either a model type + or a IO type. Required. + :type registered_asn: ~azure.mgmt.peering.models.PeeringRegisteredAsn or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredAsn] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(registered_asn, (IO, bytes)): + _content = registered_asn + else: + _json = self._serialize.body(registered_asn, "PeeringRegisteredAsn") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_asn_name=registered_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PeeringRegisteredAsn", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PeeringRegisteredAsn", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_name: str, registered_asn_name: str, **kwargs: Any + ) -> None: + """Deletes an existing registered ASN with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the registered ASN. Required. + :type registered_asn_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_asn_name=registered_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}"} # type: ignore + + @distributed_trace + def list_by_peering( + self, resource_group_name: str, peering_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PeeringRegisteredAsn"]: + """Lists all registered ASNs under the given subscription, resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringRegisteredAsn or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringRegisteredAsn] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredAsnListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_peering.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringRegisteredAsnListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_peering.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_registered_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_registered_prefixes_operations.py new file mode 100644 index 000000000000..2dd0e3ecd6dc --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_registered_prefixes_operations.py @@ -0,0 +1,511 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._registered_prefixes_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_peering_request, + build_validate_request, +) +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RegisteredPrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`registered_prefixes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, peering_name: str, registered_prefix_name: str, **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Gets an existing registered prefix with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefix] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}"} # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_prefix_name: str, + registered_prefix: _models.PeeringRegisteredPrefix, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Creates a new registered prefix with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :param registered_prefix: The properties needed to create a registered prefix. Required. + :type registered_prefix: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_prefix_name: str, + registered_prefix: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Creates a new registered prefix with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :param registered_prefix: The properties needed to create a registered prefix. Required. + :type registered_prefix: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_prefix_name: str, + registered_prefix: Union[_models.PeeringRegisteredPrefix, IO], + **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Creates a new registered prefix with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :param registered_prefix: The properties needed to create a registered prefix. Is either a + model type or a IO type. Required. + :type registered_prefix: ~azure.mgmt.peering.models.PeeringRegisteredPrefix or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefix] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(registered_prefix, (IO, bytes)): + _content = registered_prefix + else: + _json = self._serialize.body(registered_prefix, "PeeringRegisteredPrefix") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_name: str, registered_prefix_name: str, **kwargs: Any + ) -> None: + """Deletes an existing registered prefix with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}"} # type: ignore + + @distributed_trace + def list_by_peering( + self, resource_group_name: str, peering_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PeeringRegisteredPrefix"]: + """Lists all registered prefixes under the given subscription, resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringRegisteredPrefix or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.PeeringRegisteredPrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_peering.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringRegisteredPrefixListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_peering.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes"} # type: ignore + + @distributed_trace_async + async def validate( + self, resource_group_name: str, peering_name: str, registered_prefix_name: str, **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Validates an existing registered prefix with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefix] + + request = build_validate_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + validate.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}/validate"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_rp_unbilled_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_rp_unbilled_prefixes_operations.py new file mode 100644 index 000000000000..42d17dac52ee --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/aio/operations/_rp_unbilled_prefixes_operations.py @@ -0,0 +1,152 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._rp_unbilled_prefixes_operations import build_list_request +from .._vendor import PeeringManagementClientMixinABC + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RpUnbilledPrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.aio.PeeringManagementClient`'s + :attr:`rp_unbilled_prefixes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, peering_name: str, consolidate: Optional[bool] = None, **kwargs: Any + ) -> AsyncIterable["_models.RpUnbilledPrefix"]: + """Lists all of the RP unbilled prefixes for the specified peering. + + :param resource_group_name: The Azure resource group name. Required. + :type resource_group_name: str + :param peering_name: The peering name. Required. + :type peering_name: str + :param consolidate: Flag to enable consolidation prefixes. Default value is None. + :type consolidate: bool + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RpUnbilledPrefix or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.peering.models.RpUnbilledPrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RpUnbilledPrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + consolidate=consolidate, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("RpUnbilledPrefixListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/rpUnbilledPrefixes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/__init__.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/__init__.py index 7ecac278e357..abe035c843d2 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/__init__.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/__init__.py @@ -6,149 +6,166 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import BgpSession - from ._models_py3 import CheckServiceProviderAvailabilityInput - from ._models_py3 import ContactInfo - from ._models_py3 import DirectConnection - from ._models_py3 import DirectPeeringFacility - from ._models_py3 import ErrorResponse - from ._models_py3 import ExchangeConnection - from ._models_py3 import ExchangePeeringFacility - from ._models_py3 import Operation - from ._models_py3 import OperationDisplayInfo - from ._models_py3 import OperationListResult - from ._models_py3 import PeerAsn - from ._models_py3 import PeerAsnListResult - from ._models_py3 import Peering - from ._models_py3 import PeeringBandwidthOffer - from ._models_py3 import PeeringListResult - from ._models_py3 import PeeringLocation - from ._models_py3 import PeeringLocationListResult - from ._models_py3 import PeeringLocationPropertiesDirect - from ._models_py3 import PeeringLocationPropertiesExchange - from ._models_py3 import PeeringPropertiesDirect - from ._models_py3 import PeeringPropertiesExchange - from ._models_py3 import PeeringService - from ._models_py3 import PeeringServiceListResult - from ._models_py3 import PeeringServiceLocation - from ._models_py3 import PeeringServiceLocationListResult - from ._models_py3 import PeeringServicePrefix - from ._models_py3 import PeeringServicePrefixListResult - from ._models_py3 import PeeringServiceProvider - from ._models_py3 import PeeringServiceProviderListResult - from ._models_py3 import PeeringSku - from ._models_py3 import Resource - from ._models_py3 import ResourceTags - from ._models_py3 import SubResource -except (SyntaxError, ImportError): - from ._models import BgpSession # type: ignore - from ._models import CheckServiceProviderAvailabilityInput # type: ignore - from ._models import ContactInfo # type: ignore - from ._models import DirectConnection # type: ignore - from ._models import DirectPeeringFacility # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import ExchangeConnection # type: ignore - from ._models import ExchangePeeringFacility # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplayInfo # type: ignore - from ._models import OperationListResult # type: ignore - from ._models import PeerAsn # type: ignore - from ._models import PeerAsnListResult # type: ignore - from ._models import Peering # type: ignore - from ._models import PeeringBandwidthOffer # type: ignore - from ._models import PeeringListResult # type: ignore - from ._models import PeeringLocation # type: ignore - from ._models import PeeringLocationListResult # type: ignore - from ._models import PeeringLocationPropertiesDirect # type: ignore - from ._models import PeeringLocationPropertiesExchange # type: ignore - from ._models import PeeringPropertiesDirect # type: ignore - from ._models import PeeringPropertiesExchange # type: ignore - from ._models import PeeringService # type: ignore - from ._models import PeeringServiceListResult # type: ignore - from ._models import PeeringServiceLocation # type: ignore - from ._models import PeeringServiceLocationListResult # type: ignore - from ._models import PeeringServicePrefix # type: ignore - from ._models import PeeringServicePrefixListResult # type: ignore - from ._models import PeeringServiceProvider # type: ignore - from ._models import PeeringServiceProviderListResult # type: ignore - from ._models import PeeringSku # type: ignore - from ._models import Resource # type: ignore - from ._models import ResourceTags # type: ignore - from ._models import SubResource # type: ignore +from ._models_py3 import BgpSession +from ._models_py3 import CdnPeeringPrefix +from ._models_py3 import CdnPeeringPrefixListResult +from ._models_py3 import CheckServiceProviderAvailabilityInput +from ._models_py3 import ConnectionMonitorTest +from ._models_py3 import ConnectionMonitorTestListResult +from ._models_py3 import ContactDetail +from ._models_py3 import DirectConnection +from ._models_py3 import DirectPeeringFacility +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import ExchangeConnection +from ._models_py3 import ExchangePeeringFacility +from ._models_py3 import LogAnalyticsWorkspaceProperties +from ._models_py3 import LookingGlassOutput +from ._models_py3 import MetricDimension +from ._models_py3 import MetricSpecification +from ._models_py3 import Operation +from ._models_py3 import OperationDisplayInfo +from ._models_py3 import OperationListResult +from ._models_py3 import PeerAsn +from ._models_py3 import PeerAsnListResult +from ._models_py3 import Peering +from ._models_py3 import PeeringBandwidthOffer +from ._models_py3 import PeeringListResult +from ._models_py3 import PeeringLocation +from ._models_py3 import PeeringLocationListResult +from ._models_py3 import PeeringLocationPropertiesDirect +from ._models_py3 import PeeringLocationPropertiesExchange +from ._models_py3 import PeeringPropertiesDirect +from ._models_py3 import PeeringPropertiesExchange +from ._models_py3 import PeeringReceivedRoute +from ._models_py3 import PeeringReceivedRouteListResult +from ._models_py3 import PeeringRegisteredAsn +from ._models_py3 import PeeringRegisteredAsnListResult +from ._models_py3 import PeeringRegisteredPrefix +from ._models_py3 import PeeringRegisteredPrefixListResult +from ._models_py3 import PeeringService +from ._models_py3 import PeeringServiceCountry +from ._models_py3 import PeeringServiceCountryListResult +from ._models_py3 import PeeringServiceListResult +from ._models_py3 import PeeringServiceLocation +from ._models_py3 import PeeringServiceLocationListResult +from ._models_py3 import PeeringServicePrefix +from ._models_py3 import PeeringServicePrefixEvent +from ._models_py3 import PeeringServicePrefixListResult +from ._models_py3 import PeeringServiceProvider +from ._models_py3 import PeeringServiceProviderListResult +from ._models_py3 import PeeringServiceSku +from ._models_py3 import PeeringSku +from ._models_py3 import Resource +from ._models_py3 import ResourceTags +from ._models_py3 import RpUnbilledPrefix +from ._models_py3 import RpUnbilledPrefixListResult +from ._models_py3 import ServiceSpecification +from ._models_py3 import SubResource -from ._peering_management_client_enums import ( - ConnectionState, - DirectPeeringType, - Enum0, - Enum1, - Enum14, - Enum15, - Family, - Kind, - LearnedType, - Name, - PrefixValidationState, - ProvisioningState, - SessionAddressProvider, - SessionStateV4, - SessionStateV6, - Size, - Tier, - ValidationState, -) +from ._peering_management_client_enums import Command +from ._peering_management_client_enums import ConnectionState +from ._peering_management_client_enums import DirectPeeringType +from ._peering_management_client_enums import Enum0 +from ._peering_management_client_enums import Family +from ._peering_management_client_enums import Kind +from ._peering_management_client_enums import LearnedType +from ._peering_management_client_enums import LegacyPeeringsKind +from ._peering_management_client_enums import LookingGlassCommand +from ._peering_management_client_enums import LookingGlassSourceType +from ._peering_management_client_enums import PeeringLocationsDirectPeeringType +from ._peering_management_client_enums import PeeringLocationsKind +from ._peering_management_client_enums import PrefixValidationState +from ._peering_management_client_enums import ProvisioningState +from ._peering_management_client_enums import Role +from ._peering_management_client_enums import SessionAddressProvider +from ._peering_management_client_enums import SessionStateV4 +from ._peering_management_client_enums import SessionStateV6 +from ._peering_management_client_enums import Size +from ._peering_management_client_enums import Tier +from ._peering_management_client_enums import ValidationState +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'BgpSession', - 'CheckServiceProviderAvailabilityInput', - 'ContactInfo', - 'DirectConnection', - 'DirectPeeringFacility', - 'ErrorResponse', - 'ExchangeConnection', - 'ExchangePeeringFacility', - 'Operation', - 'OperationDisplayInfo', - 'OperationListResult', - 'PeerAsn', - 'PeerAsnListResult', - 'Peering', - 'PeeringBandwidthOffer', - 'PeeringListResult', - 'PeeringLocation', - 'PeeringLocationListResult', - 'PeeringLocationPropertiesDirect', - 'PeeringLocationPropertiesExchange', - 'PeeringPropertiesDirect', - 'PeeringPropertiesExchange', - 'PeeringService', - 'PeeringServiceListResult', - 'PeeringServiceLocation', - 'PeeringServiceLocationListResult', - 'PeeringServicePrefix', - 'PeeringServicePrefixListResult', - 'PeeringServiceProvider', - 'PeeringServiceProviderListResult', - 'PeeringSku', - 'Resource', - 'ResourceTags', - 'SubResource', - 'ConnectionState', - 'DirectPeeringType', - 'Enum0', - 'Enum1', - 'Enum14', - 'Enum15', - 'Family', - 'Kind', - 'LearnedType', - 'Name', - 'PrefixValidationState', - 'ProvisioningState', - 'SessionAddressProvider', - 'SessionStateV4', - 'SessionStateV6', - 'Size', - 'Tier', - 'ValidationState', + "BgpSession", + "CdnPeeringPrefix", + "CdnPeeringPrefixListResult", + "CheckServiceProviderAvailabilityInput", + "ConnectionMonitorTest", + "ConnectionMonitorTestListResult", + "ContactDetail", + "DirectConnection", + "DirectPeeringFacility", + "ErrorDetail", + "ErrorResponse", + "ExchangeConnection", + "ExchangePeeringFacility", + "LogAnalyticsWorkspaceProperties", + "LookingGlassOutput", + "MetricDimension", + "MetricSpecification", + "Operation", + "OperationDisplayInfo", + "OperationListResult", + "PeerAsn", + "PeerAsnListResult", + "Peering", + "PeeringBandwidthOffer", + "PeeringListResult", + "PeeringLocation", + "PeeringLocationListResult", + "PeeringLocationPropertiesDirect", + "PeeringLocationPropertiesExchange", + "PeeringPropertiesDirect", + "PeeringPropertiesExchange", + "PeeringReceivedRoute", + "PeeringReceivedRouteListResult", + "PeeringRegisteredAsn", + "PeeringRegisteredAsnListResult", + "PeeringRegisteredPrefix", + "PeeringRegisteredPrefixListResult", + "PeeringService", + "PeeringServiceCountry", + "PeeringServiceCountryListResult", + "PeeringServiceListResult", + "PeeringServiceLocation", + "PeeringServiceLocationListResult", + "PeeringServicePrefix", + "PeeringServicePrefixEvent", + "PeeringServicePrefixListResult", + "PeeringServiceProvider", + "PeeringServiceProviderListResult", + "PeeringServiceSku", + "PeeringSku", + "Resource", + "ResourceTags", + "RpUnbilledPrefix", + "RpUnbilledPrefixListResult", + "ServiceSpecification", + "SubResource", + "Command", + "ConnectionState", + "DirectPeeringType", + "Enum0", + "Family", + "Kind", + "LearnedType", + "LegacyPeeringsKind", + "LookingGlassCommand", + "LookingGlassSourceType", + "PeeringLocationsDirectPeeringType", + "PeeringLocationsKind", + "PrefixValidationState", + "ProvisioningState", + "Role", + "SessionAddressProvider", + "SessionStateV4", + "SessionStateV6", + "Size", + "Tier", + "ValidationState", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_models.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_models.py deleted file mode 100644 index 798562f58906..000000000000 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_models.py +++ /dev/null @@ -1,1191 +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 BgpSession(msrest.serialization.Model): - """The properties that define a BGP session. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param session_prefix_v4: The IPv4 prefix that contains both ends' IPv4 addresses. - :type session_prefix_v4: str - :param session_prefix_v6: The IPv6 prefix that contains both ends' IPv6 addresses. - :type session_prefix_v6: str - :ivar microsoft_session_i_pv4_address: The IPv4 session address on Microsoft's end. - :vartype microsoft_session_i_pv4_address: str - :ivar microsoft_session_i_pv6_address: The IPv6 session address on Microsoft's end. - :vartype microsoft_session_i_pv6_address: str - :param peer_session_i_pv4_address: The IPv4 session address on peer's end. - :type peer_session_i_pv4_address: str - :param peer_session_i_pv6_address: The IPv6 session address on peer's end. - :type peer_session_i_pv6_address: str - :ivar session_state_v4: The state of the IPv4 session. Possible values include: "None", "Idle", - "Connect", "Active", "OpenSent", "OpenConfirm", "OpenReceived", "Established", "PendingAdd", - "PendingUpdate", "PendingRemove". - :vartype session_state_v4: str or ~azure.mgmt.peering.models.SessionStateV4 - :ivar session_state_v6: The state of the IPv6 session. Possible values include: "None", "Idle", - "Connect", "Active", "OpenSent", "OpenConfirm", "OpenReceived", "Established", "PendingAdd", - "PendingUpdate", "PendingRemove". - :vartype session_state_v6: str or ~azure.mgmt.peering.models.SessionStateV6 - :param max_prefixes_advertised_v4: The maximum number of prefixes advertised over the IPv4 - session. - :type max_prefixes_advertised_v4: int - :param max_prefixes_advertised_v6: The maximum number of prefixes advertised over the IPv6 - session. - :type max_prefixes_advertised_v6: int - :param md5_authentication_key: The MD5 authentication key of the session. - :type md5_authentication_key: str - """ - - _validation = { - 'microsoft_session_i_pv4_address': {'readonly': True}, - 'microsoft_session_i_pv6_address': {'readonly': True}, - 'session_state_v4': {'readonly': True}, - 'session_state_v6': {'readonly': True}, - } - - _attribute_map = { - 'session_prefix_v4': {'key': 'sessionPrefixV4', 'type': 'str'}, - 'session_prefix_v6': {'key': 'sessionPrefixV6', 'type': 'str'}, - 'microsoft_session_i_pv4_address': {'key': 'microsoftSessionIPv4Address', 'type': 'str'}, - 'microsoft_session_i_pv6_address': {'key': 'microsoftSessionIPv6Address', 'type': 'str'}, - 'peer_session_i_pv4_address': {'key': 'peerSessionIPv4Address', 'type': 'str'}, - 'peer_session_i_pv6_address': {'key': 'peerSessionIPv6Address', 'type': 'str'}, - 'session_state_v4': {'key': 'sessionStateV4', 'type': 'str'}, - 'session_state_v6': {'key': 'sessionStateV6', 'type': 'str'}, - 'max_prefixes_advertised_v4': {'key': 'maxPrefixesAdvertisedV4', 'type': 'int'}, - 'max_prefixes_advertised_v6': {'key': 'maxPrefixesAdvertisedV6', 'type': 'int'}, - 'md5_authentication_key': {'key': 'md5AuthenticationKey', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BgpSession, self).__init__(**kwargs) - self.session_prefix_v4 = kwargs.get('session_prefix_v4', None) - self.session_prefix_v6 = kwargs.get('session_prefix_v6', None) - self.microsoft_session_i_pv4_address = None - self.microsoft_session_i_pv6_address = None - self.peer_session_i_pv4_address = kwargs.get('peer_session_i_pv4_address', None) - self.peer_session_i_pv6_address = kwargs.get('peer_session_i_pv6_address', None) - self.session_state_v4 = None - self.session_state_v6 = None - self.max_prefixes_advertised_v4 = kwargs.get('max_prefixes_advertised_v4', None) - self.max_prefixes_advertised_v6 = kwargs.get('max_prefixes_advertised_v6', None) - self.md5_authentication_key = kwargs.get('md5_authentication_key', None) - - -class CheckServiceProviderAvailabilityInput(msrest.serialization.Model): - """Class for CheckServiceProviderAvailabilityInput. - - :param peering_service_location: Gets or sets the PeeringServiceLocation. - :type peering_service_location: str - :param peering_service_provider: Gets or sets the PeeringServiceProvider. - :type peering_service_provider: str - """ - - _attribute_map = { - 'peering_service_location': {'key': 'peeringServiceLocation', 'type': 'str'}, - 'peering_service_provider': {'key': 'peeringServiceProvider', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CheckServiceProviderAvailabilityInput, self).__init__(**kwargs) - self.peering_service_location = kwargs.get('peering_service_location', None) - self.peering_service_provider = kwargs.get('peering_service_provider', None) - - -class ContactInfo(msrest.serialization.Model): - """The contact information of the peer. - - :param emails: The list of email addresses. - :type emails: list[str] - :param phone: The list of contact numbers. - :type phone: list[str] - """ - - _attribute_map = { - 'emails': {'key': 'emails', 'type': '[str]'}, - 'phone': {'key': 'phone', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(ContactInfo, self).__init__(**kwargs) - self.emails = kwargs.get('emails', None) - self.phone = kwargs.get('phone', None) - - -class DirectConnection(msrest.serialization.Model): - """The properties that define a direct connection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param bandwidth_in_mbps: The bandwidth of the connection. - :type bandwidth_in_mbps: int - :param provisioned_bandwidth_in_mbps: The bandwidth that is actually provisioned. - :type provisioned_bandwidth_in_mbps: int - :param session_address_provider: The field indicating if Microsoft provides session ip - addresses. Possible values include: "Microsoft", "Peer". - :type session_address_provider: str or ~azure.mgmt.peering.models.SessionAddressProvider - :param use_for_peering_service: The flag that indicates whether or not the connection is used - for peering service. - :type use_for_peering_service: bool - :param peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection has - to be set up. - :type peering_db_facility_id: int - :ivar connection_state: The state of the connection. Possible values include: "None", - "PendingApproval", "Approved", "ProvisioningStarted", "ProvisioningFailed", - "ProvisioningCompleted", "Validating", "Active". - :vartype connection_state: str or ~azure.mgmt.peering.models.ConnectionState - :param bgp_session: The BGP session associated with the connection. - :type bgp_session: ~azure.mgmt.peering.models.BgpSession - :param connection_identifier: The unique identifier (GUID) for the connection. - :type connection_identifier: str - """ - - _validation = { - 'connection_state': {'readonly': True}, - } - - _attribute_map = { - 'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'}, - 'provisioned_bandwidth_in_mbps': {'key': 'provisionedBandwidthInMbps', 'type': 'int'}, - 'session_address_provider': {'key': 'sessionAddressProvider', 'type': 'str'}, - 'use_for_peering_service': {'key': 'useForPeeringService', 'type': 'bool'}, - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'connection_state': {'key': 'connectionState', 'type': 'str'}, - 'bgp_session': {'key': 'bgpSession', 'type': 'BgpSession'}, - 'connection_identifier': {'key': 'connectionIdentifier', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DirectConnection, self).__init__(**kwargs) - self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None) - self.provisioned_bandwidth_in_mbps = kwargs.get('provisioned_bandwidth_in_mbps', None) - self.session_address_provider = kwargs.get('session_address_provider', None) - self.use_for_peering_service = kwargs.get('use_for_peering_service', None) - self.peering_db_facility_id = kwargs.get('peering_db_facility_id', None) - self.connection_state = None - self.bgp_session = kwargs.get('bgp_session', None) - self.connection_identifier = kwargs.get('connection_identifier', None) - - -class DirectPeeringFacility(msrest.serialization.Model): - """The properties that define a direct peering facility. - - :param address: The address of the direct peering facility. - :type address: str - :param direct_peering_type: The type of the direct peering. Possible values include: "Edge", - "Transit", "Cdn", "Internal". - :type direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType - :param peering_db_facility_id: The PeeringDB.com ID of the facility. - :type peering_db_facility_id: int - :param peering_db_facility_link: The PeeringDB.com URL of the facility. - :type peering_db_facility_link: str - """ - - _attribute_map = { - 'address': {'key': 'address', 'type': 'str'}, - 'direct_peering_type': {'key': 'directPeeringType', 'type': 'str'}, - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'peering_db_facility_link': {'key': 'peeringDBFacilityLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DirectPeeringFacility, self).__init__(**kwargs) - self.address = kwargs.get('address', None) - self.direct_peering_type = kwargs.get('direct_peering_type', None) - self.peering_db_facility_id = kwargs.get('peering_db_facility_id', None) - self.peering_db_facility_link = kwargs.get('peering_db_facility_link', None) - - -class ErrorResponse(msrest.serialization.Model): - """The error response that indicates why an operation has failed. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :vartype message: str - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.code = None - self.message = None - - -class ExchangeConnection(msrest.serialization.Model): - """The properties that define an exchange connection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection has - to be set up. - :type peering_db_facility_id: int - :ivar connection_state: The state of the connection. Possible values include: "None", - "PendingApproval", "Approved", "ProvisioningStarted", "ProvisioningFailed", - "ProvisioningCompleted", "Validating", "Active". - :vartype connection_state: str or ~azure.mgmt.peering.models.ConnectionState - :param bgp_session: The BGP session associated with the connection. - :type bgp_session: ~azure.mgmt.peering.models.BgpSession - :param connection_identifier: The unique identifier (GUID) for the connection. - :type connection_identifier: str - """ - - _validation = { - 'connection_state': {'readonly': True}, - } - - _attribute_map = { - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'connection_state': {'key': 'connectionState', 'type': 'str'}, - 'bgp_session': {'key': 'bgpSession', 'type': 'BgpSession'}, - 'connection_identifier': {'key': 'connectionIdentifier', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExchangeConnection, self).__init__(**kwargs) - self.peering_db_facility_id = kwargs.get('peering_db_facility_id', None) - self.connection_state = None - self.bgp_session = kwargs.get('bgp_session', None) - self.connection_identifier = kwargs.get('connection_identifier', None) - - -class ExchangePeeringFacility(msrest.serialization.Model): - """The properties that define an exchange peering facility. - - :param exchange_name: The name of the exchange peering facility. - :type exchange_name: str - :param bandwidth_in_mbps: The bandwidth of the connection between Microsoft and the exchange - peering facility. - :type bandwidth_in_mbps: int - :param microsoft_i_pv4_address: The IPv4 address of Microsoft at the exchange peering facility. - :type microsoft_i_pv4_address: str - :param microsoft_i_pv6_address: The IPv6 address of Microsoft at the exchange peering facility. - :type microsoft_i_pv6_address: str - :param facility_i_pv4_prefix: The IPv4 prefixes associated with the exchange peering facility. - :type facility_i_pv4_prefix: str - :param facility_i_pv6_prefix: The IPv6 prefixes associated with the exchange peering facility. - :type facility_i_pv6_prefix: str - :param peering_db_facility_id: The PeeringDB.com ID of the facility. - :type peering_db_facility_id: int - :param peering_db_facility_link: The PeeringDB.com URL of the facility. - :type peering_db_facility_link: str - """ - - _attribute_map = { - 'exchange_name': {'key': 'exchangeName', 'type': 'str'}, - 'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'}, - 'microsoft_i_pv4_address': {'key': 'microsoftIPv4Address', 'type': 'str'}, - 'microsoft_i_pv6_address': {'key': 'microsoftIPv6Address', 'type': 'str'}, - 'facility_i_pv4_prefix': {'key': 'facilityIPv4Prefix', 'type': 'str'}, - 'facility_i_pv6_prefix': {'key': 'facilityIPv6Prefix', 'type': 'str'}, - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'peering_db_facility_link': {'key': 'peeringDBFacilityLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExchangePeeringFacility, self).__init__(**kwargs) - self.exchange_name = kwargs.get('exchange_name', None) - self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None) - self.microsoft_i_pv4_address = kwargs.get('microsoft_i_pv4_address', None) - self.microsoft_i_pv6_address = kwargs.get('microsoft_i_pv6_address', None) - self.facility_i_pv4_prefix = kwargs.get('facility_i_pv4_prefix', None) - self.facility_i_pv6_prefix = kwargs.get('facility_i_pv6_prefix', None) - self.peering_db_facility_id = kwargs.get('peering_db_facility_id', None) - self.peering_db_facility_link = kwargs.get('peering_db_facility_link', None) - - -class Operation(msrest.serialization.Model): - """The peering API operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the operation. - :vartype name: str - :ivar display: The information related to the operation. - :vartype display: ~azure.mgmt.peering.models.OperationDisplayInfo - :ivar is_data_action: The flag that indicates whether the operation applies to data plane. - :vartype is_data_action: bool - """ - - _validation = { - 'name': {'readonly': True}, - 'display': {'readonly': True}, - 'is_data_action': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplayInfo'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = None - self.display = None - self.is_data_action = None - - -class OperationDisplayInfo(msrest.serialization.Model): - """The information related to the operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: The name of the resource provider. - :vartype provider: str - :ivar resource: The type of the resource. - :vartype resource: str - :ivar operation: The name of the operation. - :vartype operation: str - :ivar description: The description of the operation. - :vartype description: str - """ - - _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, - } - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplayInfo, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None - - -class OperationListResult(msrest.serialization.Model): - """The paginated list of peering API operations. - - :param value: The list of peering API operations. - :type value: list[~azure.mgmt.peering.models.Operation] - :param next_link: The link to fetch the next page of peering API operations. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class Resource(msrest.serialization.Model): - """The ARM resource class. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.name = None - self.id = None - self.type = None - - -class PeerAsn(Resource): - """The essential information related to the peer's ASN. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - :param peer_asn: The Autonomous System Number (ASN) of the peer. - :type peer_asn: int - :param peer_contact_info: The contact information of the peer. - :type peer_contact_info: ~azure.mgmt.peering.models.ContactInfo - :param peer_name: The name of the peer. - :type peer_name: str - :param validation_state: The validation state of the ASN associated with the peer. Possible - values include: "None", "Pending", "Approved", "Failed". - :type validation_state: str or ~azure.mgmt.peering.models.ValidationState - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'peer_asn': {'key': 'properties.peerAsn', 'type': 'int'}, - 'peer_contact_info': {'key': 'properties.peerContactInfo', 'type': 'ContactInfo'}, - 'peer_name': {'key': 'properties.peerName', 'type': 'str'}, - 'validation_state': {'key': 'properties.validationState', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeerAsn, self).__init__(**kwargs) - self.peer_asn = kwargs.get('peer_asn', None) - self.peer_contact_info = kwargs.get('peer_contact_info', None) - self.peer_name = kwargs.get('peer_name', None) - self.validation_state = kwargs.get('validation_state', None) - - -class PeerAsnListResult(msrest.serialization.Model): - """The paginated list of peer ASNs. - - :param value: The list of peer ASNs. - :type value: list[~azure.mgmt.peering.models.PeerAsn] - :param next_link: The link to fetch the next page of peer ASNs. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[PeerAsn]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeerAsnListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class Peering(Resource): - """Peering is a logical representation of a set of connections to the Microsoft Cloud Edge at a location. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - :param sku: Required. The SKU that defines the tier and kind of the peering. - :type sku: ~azure.mgmt.peering.models.PeeringSku - :param kind: Required. The kind of the peering. Possible values include: "Direct", "Exchange". - :type kind: str or ~azure.mgmt.peering.models.Kind - :param location: Required. The location of the resource. - :type location: str - :param tags: A set of tags. The resource tags. - :type tags: dict[str, str] - :param direct: The properties that define a direct peering. - :type direct: ~azure.mgmt.peering.models.PeeringPropertiesDirect - :param exchange: The properties that define an exchange peering. - :type exchange: ~azure.mgmt.peering.models.PeeringPropertiesExchange - :param peering_location: The location of the peering. - :type peering_location: str - :ivar provisioning_state: The provisioning state of the resource. Possible values include: - "Succeeded", "Updating", "Deleting", "Failed". - :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'sku': {'required': True}, - 'kind': {'required': True}, - 'location': {'required': True}, - 'provisioning_state': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'PeeringSku'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'direct': {'key': 'properties.direct', 'type': 'PeeringPropertiesDirect'}, - 'exchange': {'key': 'properties.exchange', 'type': 'PeeringPropertiesExchange'}, - 'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Peering, self).__init__(**kwargs) - self.sku = kwargs['sku'] - self.kind = kwargs['kind'] - self.location = kwargs['location'] - self.tags = kwargs.get('tags', None) - self.direct = kwargs.get('direct', None) - self.exchange = kwargs.get('exchange', None) - self.peering_location = kwargs.get('peering_location', None) - self.provisioning_state = None - - -class PeeringBandwidthOffer(msrest.serialization.Model): - """The properties that define a peering bandwidth offer. - - :param offer_name: The name of the bandwidth offer. - :type offer_name: str - :param value_in_mbps: The value of the bandwidth offer in Mbps. - :type value_in_mbps: int - """ - - _attribute_map = { - 'offer_name': {'key': 'offerName', 'type': 'str'}, - 'value_in_mbps': {'key': 'valueInMbps', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringBandwidthOffer, self).__init__(**kwargs) - self.offer_name = kwargs.get('offer_name', None) - self.value_in_mbps = kwargs.get('value_in_mbps', None) - - -class PeeringListResult(msrest.serialization.Model): - """The paginated list of peerings. - - :param value: The list of peerings. - :type value: list[~azure.mgmt.peering.models.Peering] - :param next_link: The link to fetch the next page of peerings. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Peering]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class PeeringLocation(Resource): - """Peering location is where connectivity could be established to the Microsoft Cloud Edge. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - :param kind: The kind of peering that the peering location supports. Possible values include: - "Direct", "Exchange". - :type kind: str or ~azure.mgmt.peering.models.Kind - :param direct: The properties that define a direct peering location. - :type direct: ~azure.mgmt.peering.models.PeeringLocationPropertiesDirect - :param exchange: The properties that define an exchange peering location. - :type exchange: ~azure.mgmt.peering.models.PeeringLocationPropertiesExchange - :param peering_location: The name of the peering location. - :type peering_location: str - :param country: The country in which the peering location exists. - :type country: str - :param azure_region: The Azure region associated with the peering location. - :type azure_region: str - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'direct': {'key': 'properties.direct', 'type': 'PeeringLocationPropertiesDirect'}, - 'exchange': {'key': 'properties.exchange', 'type': 'PeeringLocationPropertiesExchange'}, - 'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'}, - 'country': {'key': 'properties.country', 'type': 'str'}, - 'azure_region': {'key': 'properties.azureRegion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringLocation, self).__init__(**kwargs) - self.kind = kwargs.get('kind', None) - self.direct = kwargs.get('direct', None) - self.exchange = kwargs.get('exchange', None) - self.peering_location = kwargs.get('peering_location', None) - self.country = kwargs.get('country', None) - self.azure_region = kwargs.get('azure_region', None) - - -class PeeringLocationListResult(msrest.serialization.Model): - """The paginated list of peering locations. - - :param value: The list of peering locations. - :type value: list[~azure.mgmt.peering.models.PeeringLocation] - :param next_link: The link to fetch the next page of peering locations. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringLocation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringLocationListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class PeeringLocationPropertiesDirect(msrest.serialization.Model): - """The properties that define a direct peering location. - - :param peering_facilities: The list of direct peering facilities at the peering location. - :type peering_facilities: list[~azure.mgmt.peering.models.DirectPeeringFacility] - :param bandwidth_offers: The list of bandwidth offers available at the peering location. - :type bandwidth_offers: list[~azure.mgmt.peering.models.PeeringBandwidthOffer] - """ - - _attribute_map = { - 'peering_facilities': {'key': 'peeringFacilities', 'type': '[DirectPeeringFacility]'}, - 'bandwidth_offers': {'key': 'bandwidthOffers', 'type': '[PeeringBandwidthOffer]'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringLocationPropertiesDirect, self).__init__(**kwargs) - self.peering_facilities = kwargs.get('peering_facilities', None) - self.bandwidth_offers = kwargs.get('bandwidth_offers', None) - - -class PeeringLocationPropertiesExchange(msrest.serialization.Model): - """The properties that define an exchange peering location. - - :param peering_facilities: The list of exchange peering facilities at the peering location. - :type peering_facilities: list[~azure.mgmt.peering.models.ExchangePeeringFacility] - """ - - _attribute_map = { - 'peering_facilities': {'key': 'peeringFacilities', 'type': '[ExchangePeeringFacility]'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringLocationPropertiesExchange, self).__init__(**kwargs) - self.peering_facilities = kwargs.get('peering_facilities', None) - - -class PeeringPropertiesDirect(msrest.serialization.Model): - """The properties that define a direct peering. - - :param connections: The set of connections that constitute a direct peering. - :type connections: list[~azure.mgmt.peering.models.DirectConnection] - :param use_for_peering_service: The flag that indicates whether or not the peering is used for - peering service. - :type use_for_peering_service: bool - :param peer_asn: The reference of the peer ASN. - :type peer_asn: ~azure.mgmt.peering.models.SubResource - :param direct_peering_type: The type of direct peering. Possible values include: "Edge", - "Transit", "Cdn", "Internal". - :type direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType - """ - - _attribute_map = { - 'connections': {'key': 'connections', 'type': '[DirectConnection]'}, - 'use_for_peering_service': {'key': 'useForPeeringService', 'type': 'bool'}, - 'peer_asn': {'key': 'peerAsn', 'type': 'SubResource'}, - 'direct_peering_type': {'key': 'directPeeringType', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringPropertiesDirect, self).__init__(**kwargs) - self.connections = kwargs.get('connections', None) - self.use_for_peering_service = kwargs.get('use_for_peering_service', None) - self.peer_asn = kwargs.get('peer_asn', None) - self.direct_peering_type = kwargs.get('direct_peering_type', None) - - -class PeeringPropertiesExchange(msrest.serialization.Model): - """The properties that define an exchange peering. - - :param connections: The set of connections that constitute an exchange peering. - :type connections: list[~azure.mgmt.peering.models.ExchangeConnection] - :param peer_asn: The reference of the peer ASN. - :type peer_asn: ~azure.mgmt.peering.models.SubResource - """ - - _attribute_map = { - 'connections': {'key': 'connections', 'type': '[ExchangeConnection]'}, - 'peer_asn': {'key': 'peerAsn', 'type': 'SubResource'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringPropertiesExchange, self).__init__(**kwargs) - self.connections = kwargs.get('connections', None) - self.peer_asn = kwargs.get('peer_asn', None) - - -class PeeringService(Resource): - """Peering Service. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - :param location: Required. The location of the resource. - :type location: str - :param tags: A set of tags. The resource tags. - :type tags: dict[str, str] - :param peering_service_location: The PeeringServiceLocation of the Customer. - :type peering_service_location: str - :param peering_service_provider: The MAPS Provider Name. - :type peering_service_provider: str - :ivar provisioning_state: The provisioning state of the resource. Possible values include: - "Succeeded", "Updating", "Deleting", "Failed". - :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'provisioning_state': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'peering_service_location': {'key': 'properties.peeringServiceLocation', 'type': 'str'}, - 'peering_service_provider': {'key': 'properties.peeringServiceProvider', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringService, self).__init__(**kwargs) - self.location = kwargs['location'] - self.tags = kwargs.get('tags', None) - self.peering_service_location = kwargs.get('peering_service_location', None) - self.peering_service_provider = kwargs.get('peering_service_provider', None) - self.provisioning_state = None - - -class PeeringServiceListResult(msrest.serialization.Model): - """The paginated list of peering services. - - :param value: The list of peering services. - :type value: list[~azure.mgmt.peering.models.PeeringService] - :param next_link: The link to fetch the next page of peering services. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringService]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringServiceListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class PeeringServiceLocation(Resource): - """PeeringService location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - :param country: Country of the customer. - :type country: str - :param state: State of the customer. - :type state: str - :param azure_region: Azure region for the location. - :type azure_region: str - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'country': {'key': 'properties.country', 'type': 'str'}, - 'state': {'key': 'properties.state', 'type': 'str'}, - 'azure_region': {'key': 'properties.azureRegion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringServiceLocation, self).__init__(**kwargs) - self.country = kwargs.get('country', None) - self.state = kwargs.get('state', None) - self.azure_region = kwargs.get('azure_region', None) - - -class PeeringServiceLocationListResult(msrest.serialization.Model): - """The paginated list of peering service locations. - - :param value: The list of peering service locations. - :type value: list[~azure.mgmt.peering.models.PeeringServiceLocation] - :param next_link: The link to fetch the next page of peering service locations. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringServiceLocation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringServiceLocationListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class PeeringServicePrefix(Resource): - """The peering service prefix class. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - :param prefix: Valid route prefix. - :type prefix: str - :param prefix_validation_state: The prefix validation state. Possible values include: "None", - "Invalid", "Verified", "Failed", "Pending", "Unknown". - :type prefix_validation_state: str or ~azure.mgmt.peering.models.PrefixValidationState - :param learned_type: The prefix learned type. Possible values include: "None", "ViaPartner", - "ViaSession". - :type learned_type: str or ~azure.mgmt.peering.models.LearnedType - :ivar provisioning_state: The provisioning state of the resource. Possible values include: - "Succeeded", "Updating", "Deleting", "Failed". - :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'prefix': {'key': 'properties.prefix', 'type': 'str'}, - 'prefix_validation_state': {'key': 'properties.prefixValidationState', 'type': 'str'}, - 'learned_type': {'key': 'properties.learnedType', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringServicePrefix, self).__init__(**kwargs) - self.prefix = kwargs.get('prefix', None) - self.prefix_validation_state = kwargs.get('prefix_validation_state', None) - self.learned_type = kwargs.get('learned_type', None) - self.provisioning_state = None - - -class PeeringServicePrefixListResult(msrest.serialization.Model): - """The paginated list of [T]. - - :param value: The list of [T]. - :type value: list[~azure.mgmt.peering.models.PeeringServicePrefix] - :param next_link: The link to fetch the next page of [T]. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringServicePrefix]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringServicePrefixListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class PeeringServiceProvider(Resource): - """PeeringService provider. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - :param service_provider_name: The name of the service provider. - :type service_provider_name: str - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'service_provider_name': {'key': 'properties.serviceProviderName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringServiceProvider, self).__init__(**kwargs) - self.service_provider_name = kwargs.get('service_provider_name', None) - - -class PeeringServiceProviderListResult(msrest.serialization.Model): - """The paginated list of peering service providers. - - :param value: The list of peering service providers. - :type value: list[~azure.mgmt.peering.models.PeeringServiceProvider] - :param next_link: The link to fetch the next page of peering service providers. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringServiceProvider]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringServiceProviderListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class PeeringSku(msrest.serialization.Model): - """The SKU that defines the tier and kind of the peering. - - :param name: The name of the peering SKU. Possible values include: "Basic_Exchange_Free", - "Basic_Direct_Free", "Premium_Direct_Free", "Premium_Exchange_Metered", - "Premium_Direct_Metered", "Premium_Direct_Unlimited". - :type name: str or ~azure.mgmt.peering.models.Name - :param tier: The tier of the peering SKU. Possible values include: "Basic", "Premium". - :type tier: str or ~azure.mgmt.peering.models.Tier - :param family: The family of the peering SKU. Possible values include: "Direct", "Exchange". - :type family: str or ~azure.mgmt.peering.models.Family - :param size: The size of the peering SKU. Possible values include: "Free", "Metered", - "Unlimited". - :type size: str or ~azure.mgmt.peering.models.Size - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'tier': {'key': 'tier', 'type': 'str'}, - 'family': {'key': 'family', 'type': 'str'}, - 'size': {'key': 'size', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PeeringSku, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.tier = kwargs.get('tier', None) - self.family = kwargs.get('family', None) - self.size = kwargs.get('size', None) - - -class ResourceTags(msrest.serialization.Model): - """The resource tags. - - :param tags: A set of tags. Gets or sets the tags, a dictionary of descriptors arm object. - :type tags: dict[str, str] - """ - - _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(ResourceTags, self).__init__(**kwargs) - self.tags = kwargs.get('tags', None) - - -class SubResource(msrest.serialization.Model): - """The sub resource. - - :param id: The identifier of the referenced resource. - :type id: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SubResource, self).__init__(**kwargs) - self.id = kwargs.get('id', None) diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_models_py3.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_models_py3.py index d8d0bde9b4a6..83100b253ca4 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_models_py3.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,68 +7,67 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._peering_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class BgpSession(msrest.serialization.Model): +class BgpSession(_serialization.Model): # pylint: disable=too-many-instance-attributes """The properties that define a BGP session. Variables are only populated by the server, and will be ignored when sending a request. - :param session_prefix_v4: The IPv4 prefix that contains both ends' IPv4 addresses. - :type session_prefix_v4: str - :param session_prefix_v6: The IPv6 prefix that contains both ends' IPv6 addresses. - :type session_prefix_v6: str + :ivar session_prefix_v4: The IPv4 prefix that contains both ends' IPv4 addresses. + :vartype session_prefix_v4: str + :ivar session_prefix_v6: The IPv6 prefix that contains both ends' IPv6 addresses. + :vartype session_prefix_v6: str :ivar microsoft_session_i_pv4_address: The IPv4 session address on Microsoft's end. :vartype microsoft_session_i_pv4_address: str :ivar microsoft_session_i_pv6_address: The IPv6 session address on Microsoft's end. :vartype microsoft_session_i_pv6_address: str - :param peer_session_i_pv4_address: The IPv4 session address on peer's end. - :type peer_session_i_pv4_address: str - :param peer_session_i_pv6_address: The IPv6 session address on peer's end. - :type peer_session_i_pv6_address: str - :ivar session_state_v4: The state of the IPv4 session. Possible values include: "None", "Idle", + :ivar peer_session_i_pv4_address: The IPv4 session address on peer's end. + :vartype peer_session_i_pv4_address: str + :ivar peer_session_i_pv6_address: The IPv6 session address on peer's end. + :vartype peer_session_i_pv6_address: str + :ivar session_state_v4: The state of the IPv4 session. Known values are: "None", "Idle", "Connect", "Active", "OpenSent", "OpenConfirm", "OpenReceived", "Established", "PendingAdd", - "PendingUpdate", "PendingRemove". + "PendingUpdate", and "PendingRemove". :vartype session_state_v4: str or ~azure.mgmt.peering.models.SessionStateV4 - :ivar session_state_v6: The state of the IPv6 session. Possible values include: "None", "Idle", + :ivar session_state_v6: The state of the IPv6 session. Known values are: "None", "Idle", "Connect", "Active", "OpenSent", "OpenConfirm", "OpenReceived", "Established", "PendingAdd", - "PendingUpdate", "PendingRemove". + "PendingUpdate", and "PendingRemove". :vartype session_state_v6: str or ~azure.mgmt.peering.models.SessionStateV6 - :param max_prefixes_advertised_v4: The maximum number of prefixes advertised over the IPv4 + :ivar max_prefixes_advertised_v4: The maximum number of prefixes advertised over the IPv4 session. - :type max_prefixes_advertised_v4: int - :param max_prefixes_advertised_v6: The maximum number of prefixes advertised over the IPv6 + :vartype max_prefixes_advertised_v4: int + :ivar max_prefixes_advertised_v6: The maximum number of prefixes advertised over the IPv6 session. - :type max_prefixes_advertised_v6: int - :param md5_authentication_key: The MD5 authentication key of the session. - :type md5_authentication_key: str + :vartype max_prefixes_advertised_v6: int + :ivar md5_authentication_key: The MD5 authentication key of the session. + :vartype md5_authentication_key: str """ _validation = { - 'microsoft_session_i_pv4_address': {'readonly': True}, - 'microsoft_session_i_pv6_address': {'readonly': True}, - 'session_state_v4': {'readonly': True}, - 'session_state_v6': {'readonly': True}, + "session_state_v4": {"readonly": True}, + "session_state_v6": {"readonly": True}, } _attribute_map = { - 'session_prefix_v4': {'key': 'sessionPrefixV4', 'type': 'str'}, - 'session_prefix_v6': {'key': 'sessionPrefixV6', 'type': 'str'}, - 'microsoft_session_i_pv4_address': {'key': 'microsoftSessionIPv4Address', 'type': 'str'}, - 'microsoft_session_i_pv6_address': {'key': 'microsoftSessionIPv6Address', 'type': 'str'}, - 'peer_session_i_pv4_address': {'key': 'peerSessionIPv4Address', 'type': 'str'}, - 'peer_session_i_pv6_address': {'key': 'peerSessionIPv6Address', 'type': 'str'}, - 'session_state_v4': {'key': 'sessionStateV4', 'type': 'str'}, - 'session_state_v6': {'key': 'sessionStateV6', 'type': 'str'}, - 'max_prefixes_advertised_v4': {'key': 'maxPrefixesAdvertisedV4', 'type': 'int'}, - 'max_prefixes_advertised_v6': {'key': 'maxPrefixesAdvertisedV6', 'type': 'int'}, - 'md5_authentication_key': {'key': 'md5AuthenticationKey', 'type': 'str'}, + "session_prefix_v4": {"key": "sessionPrefixV4", "type": "str"}, + "session_prefix_v6": {"key": "sessionPrefixV6", "type": "str"}, + "microsoft_session_i_pv4_address": {"key": "microsoftSessionIPv4Address", "type": "str"}, + "microsoft_session_i_pv6_address": {"key": "microsoftSessionIPv6Address", "type": "str"}, + "peer_session_i_pv4_address": {"key": "peerSessionIPv4Address", "type": "str"}, + "peer_session_i_pv6_address": {"key": "peerSessionIPv6Address", "type": "str"}, + "session_state_v4": {"key": "sessionStateV4", "type": "str"}, + "session_state_v6": {"key": "sessionStateV6", "type": "str"}, + "max_prefixes_advertised_v4": {"key": "maxPrefixesAdvertisedV4", "type": "int"}, + "max_prefixes_advertised_v6": {"key": "maxPrefixesAdvertisedV6", "type": "int"}, + "md5_authentication_key": {"key": "md5AuthenticationKey", "type": "str"}, } def __init__( @@ -75,6 +75,8 @@ def __init__( *, session_prefix_v4: Optional[str] = None, session_prefix_v6: Optional[str] = None, + microsoft_session_i_pv4_address: Optional[str] = None, + microsoft_session_i_pv6_address: Optional[str] = None, peer_session_i_pv4_address: Optional[str] = None, peer_session_i_pv6_address: Optional[str] = None, max_prefixes_advertised_v4: Optional[int] = None, @@ -82,11 +84,33 @@ def __init__( md5_authentication_key: Optional[str] = None, **kwargs ): - super(BgpSession, self).__init__(**kwargs) + """ + :keyword session_prefix_v4: The IPv4 prefix that contains both ends' IPv4 addresses. + :paramtype session_prefix_v4: str + :keyword session_prefix_v6: The IPv6 prefix that contains both ends' IPv6 addresses. + :paramtype session_prefix_v6: str + :keyword microsoft_session_i_pv4_address: The IPv4 session address on Microsoft's end. + :paramtype microsoft_session_i_pv4_address: str + :keyword microsoft_session_i_pv6_address: The IPv6 session address on Microsoft's end. + :paramtype microsoft_session_i_pv6_address: str + :keyword peer_session_i_pv4_address: The IPv4 session address on peer's end. + :paramtype peer_session_i_pv4_address: str + :keyword peer_session_i_pv6_address: The IPv6 session address on peer's end. + :paramtype peer_session_i_pv6_address: str + :keyword max_prefixes_advertised_v4: The maximum number of prefixes advertised over the IPv4 + session. + :paramtype max_prefixes_advertised_v4: int + :keyword max_prefixes_advertised_v6: The maximum number of prefixes advertised over the IPv6 + session. + :paramtype max_prefixes_advertised_v6: int + :keyword md5_authentication_key: The MD5 authentication key of the session. + :paramtype md5_authentication_key: str + """ + super().__init__(**kwargs) self.session_prefix_v4 = session_prefix_v4 self.session_prefix_v6 = session_prefix_v6 - self.microsoft_session_i_pv4_address = None - self.microsoft_session_i_pv6_address = None + self.microsoft_session_i_pv4_address = microsoft_session_i_pv4_address + self.microsoft_session_i_pv6_address = microsoft_session_i_pv6_address self.peer_session_i_pv4_address = peer_session_i_pv4_address self.peer_session_i_pv6_address = peer_session_i_pv6_address self.session_state_v4 = None @@ -96,18 +120,134 @@ def __init__( self.md5_authentication_key = md5_authentication_key -class CheckServiceProviderAvailabilityInput(msrest.serialization.Model): +class Resource(_serialization.Model): + """The ARM resource class. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the resource. + :vartype name: str + :ivar id: The ID of the resource. + :vartype id: str + :ivar type: The type of the resource. + :vartype type: str + """ + + _validation = { + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.name = None + self.id = None + self.type = None + + +class CdnPeeringPrefix(Resource): + """The CDN peering prefix. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the resource. + :vartype name: str + :ivar id: The ID of the resource. + :vartype id: str + :ivar type: The type of the resource. + :vartype type: str + :ivar prefix: The prefix. + :vartype prefix: str + :ivar azure_region: The Azure region. + :vartype azure_region: str + :ivar azure_service: The Azure service. + :vartype azure_service: str + :ivar is_primary_region: The flag that indicates whether or not this is the primary region. + :vartype is_primary_region: bool + :ivar bgp_community: The BGP Community. + :vartype bgp_community: str + """ + + _validation = { + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "prefix": {"readonly": True}, + "azure_region": {"readonly": True}, + "azure_service": {"readonly": True}, + "is_primary_region": {"readonly": True}, + "bgp_community": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "prefix": {"key": "properties.prefix", "type": "str"}, + "azure_region": {"key": "properties.azureRegion", "type": "str"}, + "azure_service": {"key": "properties.azureService", "type": "str"}, + "is_primary_region": {"key": "properties.isPrimaryRegion", "type": "bool"}, + "bgp_community": {"key": "properties.bgpCommunity", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.prefix = None + self.azure_region = None + self.azure_service = None + self.is_primary_region = None + self.bgp_community = None + + +class CdnPeeringPrefixListResult(_serialization.Model): + """The paginated list of CDN peering prefixes. + + :ivar value: The list of CDN peering prefixes. + :vartype value: list[~azure.mgmt.peering.models.CdnPeeringPrefix] + :ivar next_link: The link to fetch the next page of CDN peering prefixes. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[CdnPeeringPrefix]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.CdnPeeringPrefix"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: The list of CDN peering prefixes. + :paramtype value: list[~azure.mgmt.peering.models.CdnPeeringPrefix] + :keyword next_link: The link to fetch the next page of CDN peering prefixes. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class CheckServiceProviderAvailabilityInput(_serialization.Model): """Class for CheckServiceProviderAvailabilityInput. - :param peering_service_location: Gets or sets the PeeringServiceLocation. - :type peering_service_location: str - :param peering_service_provider: Gets or sets the PeeringServiceProvider. - :type peering_service_provider: str + :ivar peering_service_location: Gets or sets the peering service location. + :vartype peering_service_location: str + :ivar peering_service_provider: Gets or sets the peering service provider. + :vartype peering_service_provider: str """ _attribute_map = { - 'peering_service_location': {'key': 'peeringServiceLocation', 'type': 'str'}, - 'peering_service_provider': {'key': 'peeringServiceProvider', 'type': 'str'}, + "peering_service_location": {"key": "peeringServiceLocation", "type": "str"}, + "peering_service_provider": {"key": "peeringServiceProvider", "type": "str"}, } def __init__( @@ -117,142 +257,315 @@ def __init__( peering_service_provider: Optional[str] = None, **kwargs ): - super(CheckServiceProviderAvailabilityInput, self).__init__(**kwargs) + """ + :keyword peering_service_location: Gets or sets the peering service location. + :paramtype peering_service_location: str + :keyword peering_service_provider: Gets or sets the peering service provider. + :paramtype peering_service_provider: str + """ + super().__init__(**kwargs) self.peering_service_location = peering_service_location self.peering_service_provider = peering_service_provider -class ContactInfo(msrest.serialization.Model): - """The contact information of the peer. +class ConnectionMonitorTest(Resource): + """The Connection Monitor Test class. - :param emails: The list of email addresses. - :type emails: list[str] - :param phone: The list of contact numbers. - :type phone: list[str] + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the resource. + :vartype name: str + :ivar id: The ID of the resource. + :vartype id: str + :ivar type: The type of the resource. + :vartype type: str + :ivar source_agent: The Connection Monitor test source agent. + :vartype source_agent: str + :ivar destination: The Connection Monitor test destination. + :vartype destination: str + :ivar destination_port: The Connection Monitor test destination port. + :vartype destination_port: int + :ivar test_frequency_in_sec: The Connection Monitor test frequency in seconds. + :vartype test_frequency_in_sec: int + :ivar is_test_successful: The flag that indicates if the Connection Monitor test is successful + or not. + :vartype is_test_successful: bool + :ivar path: The path representing the Connection Monitor test. + :vartype path: list[str] + :ivar provisioning_state: The provisioning state of the resource. Known values are: + "Succeeded", "Updating", "Deleting", and "Failed". + :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState """ + _validation = { + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "is_test_successful": {"readonly": True}, + "path": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + _attribute_map = { - 'emails': {'key': 'emails', 'type': '[str]'}, - 'phone': {'key': 'phone', 'type': '[str]'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "source_agent": {"key": "properties.sourceAgent", "type": "str"}, + "destination": {"key": "properties.destination", "type": "str"}, + "destination_port": {"key": "properties.destinationPort", "type": "int"}, + "test_frequency_in_sec": {"key": "properties.testFrequencyInSec", "type": "int"}, + "is_test_successful": {"key": "properties.isTestSuccessful", "type": "bool"}, + "path": {"key": "properties.path", "type": "[str]"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } def __init__( self, *, - emails: Optional[List[str]] = None, - phone: Optional[List[str]] = None, + source_agent: Optional[str] = None, + destination: Optional[str] = None, + destination_port: Optional[int] = None, + test_frequency_in_sec: Optional[int] = None, **kwargs ): - super(ContactInfo, self).__init__(**kwargs) - self.emails = emails + """ + :keyword source_agent: The Connection Monitor test source agent. + :paramtype source_agent: str + :keyword destination: The Connection Monitor test destination. + :paramtype destination: str + :keyword destination_port: The Connection Monitor test destination port. + :paramtype destination_port: int + :keyword test_frequency_in_sec: The Connection Monitor test frequency in seconds. + :paramtype test_frequency_in_sec: int + """ + super().__init__(**kwargs) + self.source_agent = source_agent + self.destination = destination + self.destination_port = destination_port + self.test_frequency_in_sec = test_frequency_in_sec + self.is_test_successful = None + self.path = None + self.provisioning_state = None + + +class ConnectionMonitorTestListResult(_serialization.Model): + """The paginated list of Connection Monitor Tests. + + :ivar value: The list of Connection Monitor Tests. + :vartype value: list[~azure.mgmt.peering.models.ConnectionMonitorTest] + :ivar next_link: The link to fetch the next page of Connection Monitor Tests. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ConnectionMonitorTest]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.ConnectionMonitorTest"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of Connection Monitor Tests. + :paramtype value: list[~azure.mgmt.peering.models.ConnectionMonitorTest] + :keyword next_link: The link to fetch the next page of Connection Monitor Tests. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ContactDetail(_serialization.Model): + """The contact detail class. + + :ivar role: The role of the contact. Known values are: "Noc", "Policy", "Technical", "Service", + "Escalation", and "Other". + :vartype role: str or ~azure.mgmt.peering.models.Role + :ivar email: The e-mail address of the contact. + :vartype email: str + :ivar phone: The phone number of the contact. + :vartype phone: str + """ + + _attribute_map = { + "role": {"key": "role", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "phone": {"key": "phone", "type": "str"}, + } + + def __init__( + self, + *, + role: Optional[Union[str, "_models.Role"]] = None, + email: Optional[str] = None, + phone: Optional[str] = None, + **kwargs + ): + """ + :keyword role: The role of the contact. Known values are: "Noc", "Policy", "Technical", + "Service", "Escalation", and "Other". + :paramtype role: str or ~azure.mgmt.peering.models.Role + :keyword email: The e-mail address of the contact. + :paramtype email: str + :keyword phone: The phone number of the contact. + :paramtype phone: str + """ + super().__init__(**kwargs) + self.role = role + self.email = email self.phone = phone -class DirectConnection(msrest.serialization.Model): +class DirectConnection(_serialization.Model): """The properties that define a direct connection. Variables are only populated by the server, and will be ignored when sending a request. - :param bandwidth_in_mbps: The bandwidth of the connection. - :type bandwidth_in_mbps: int - :param provisioned_bandwidth_in_mbps: The bandwidth that is actually provisioned. - :type provisioned_bandwidth_in_mbps: int - :param session_address_provider: The field indicating if Microsoft provides session ip - addresses. Possible values include: "Microsoft", "Peer". - :type session_address_provider: str or ~azure.mgmt.peering.models.SessionAddressProvider - :param use_for_peering_service: The flag that indicates whether or not the connection is used + :ivar bandwidth_in_mbps: The bandwidth of the connection. + :vartype bandwidth_in_mbps: int + :ivar provisioned_bandwidth_in_mbps: The bandwidth that is actually provisioned. + :vartype provisioned_bandwidth_in_mbps: int + :ivar session_address_provider: The field indicating if Microsoft provides session ip + addresses. Known values are: "Microsoft" and "Peer". + :vartype session_address_provider: str or ~azure.mgmt.peering.models.SessionAddressProvider + :ivar use_for_peering_service: The flag that indicates whether or not the connection is used for peering service. - :type use_for_peering_service: bool - :param peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection has + :vartype use_for_peering_service: bool + :ivar microsoft_tracking_id: The ID used within Microsoft's peering provisioning system to + track the connection. + :vartype microsoft_tracking_id: str + :ivar peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection has to be set up. - :type peering_db_facility_id: int - :ivar connection_state: The state of the connection. Possible values include: "None", + :vartype peering_db_facility_id: int + :ivar connection_state: The state of the connection. Known values are: "None", "PendingApproval", "Approved", "ProvisioningStarted", "ProvisioningFailed", - "ProvisioningCompleted", "Validating", "Active". + "ProvisioningCompleted", "Validating", "Active", "TypeChangeRequested", and + "TypeChangeInProgress". :vartype connection_state: str or ~azure.mgmt.peering.models.ConnectionState - :param bgp_session: The BGP session associated with the connection. - :type bgp_session: ~azure.mgmt.peering.models.BgpSession - :param connection_identifier: The unique identifier (GUID) for the connection. - :type connection_identifier: str + :ivar bgp_session: The BGP session associated with the connection. + :vartype bgp_session: ~azure.mgmt.peering.models.BgpSession + :ivar connection_identifier: The unique identifier (GUID) for the connection. + :vartype connection_identifier: str + :ivar error_message: The error message related to the connection state, if any. + :vartype error_message: str """ _validation = { - 'connection_state': {'readonly': True}, + "provisioned_bandwidth_in_mbps": {"readonly": True}, + "microsoft_tracking_id": {"readonly": True}, + "connection_state": {"readonly": True}, + "error_message": {"readonly": True}, } _attribute_map = { - 'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'}, - 'provisioned_bandwidth_in_mbps': {'key': 'provisionedBandwidthInMbps', 'type': 'int'}, - 'session_address_provider': {'key': 'sessionAddressProvider', 'type': 'str'}, - 'use_for_peering_service': {'key': 'useForPeeringService', 'type': 'bool'}, - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'connection_state': {'key': 'connectionState', 'type': 'str'}, - 'bgp_session': {'key': 'bgpSession', 'type': 'BgpSession'}, - 'connection_identifier': {'key': 'connectionIdentifier', 'type': 'str'}, + "bandwidth_in_mbps": {"key": "bandwidthInMbps", "type": "int"}, + "provisioned_bandwidth_in_mbps": {"key": "provisionedBandwidthInMbps", "type": "int"}, + "session_address_provider": {"key": "sessionAddressProvider", "type": "str"}, + "use_for_peering_service": {"key": "useForPeeringService", "type": "bool"}, + "microsoft_tracking_id": {"key": "microsoftTrackingId", "type": "str"}, + "peering_db_facility_id": {"key": "peeringDBFacilityId", "type": "int"}, + "connection_state": {"key": "connectionState", "type": "str"}, + "bgp_session": {"key": "bgpSession", "type": "BgpSession"}, + "connection_identifier": {"key": "connectionIdentifier", "type": "str"}, + "error_message": {"key": "errorMessage", "type": "str"}, } def __init__( self, *, bandwidth_in_mbps: Optional[int] = None, - provisioned_bandwidth_in_mbps: Optional[int] = None, - session_address_provider: Optional[Union[str, "SessionAddressProvider"]] = None, + session_address_provider: Optional[Union[str, "_models.SessionAddressProvider"]] = None, use_for_peering_service: Optional[bool] = None, peering_db_facility_id: Optional[int] = None, - bgp_session: Optional["BgpSession"] = None, + bgp_session: Optional["_models.BgpSession"] = None, connection_identifier: Optional[str] = None, **kwargs ): - super(DirectConnection, self).__init__(**kwargs) + """ + :keyword bandwidth_in_mbps: The bandwidth of the connection. + :paramtype bandwidth_in_mbps: int + :keyword session_address_provider: The field indicating if Microsoft provides session ip + addresses. Known values are: "Microsoft" and "Peer". + :paramtype session_address_provider: str or ~azure.mgmt.peering.models.SessionAddressProvider + :keyword use_for_peering_service: The flag that indicates whether or not the connection is used + for peering service. + :paramtype use_for_peering_service: bool + :keyword peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection + has to be set up. + :paramtype peering_db_facility_id: int + :keyword bgp_session: The BGP session associated with the connection. + :paramtype bgp_session: ~azure.mgmt.peering.models.BgpSession + :keyword connection_identifier: The unique identifier (GUID) for the connection. + :paramtype connection_identifier: str + """ + super().__init__(**kwargs) self.bandwidth_in_mbps = bandwidth_in_mbps - self.provisioned_bandwidth_in_mbps = provisioned_bandwidth_in_mbps + self.provisioned_bandwidth_in_mbps = None self.session_address_provider = session_address_provider self.use_for_peering_service = use_for_peering_service + self.microsoft_tracking_id = None self.peering_db_facility_id = peering_db_facility_id self.connection_state = None self.bgp_session = bgp_session self.connection_identifier = connection_identifier + self.error_message = None -class DirectPeeringFacility(msrest.serialization.Model): +class DirectPeeringFacility(_serialization.Model): """The properties that define a direct peering facility. - :param address: The address of the direct peering facility. - :type address: str - :param direct_peering_type: The type of the direct peering. Possible values include: "Edge", - "Transit", "Cdn", "Internal". - :type direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType - :param peering_db_facility_id: The PeeringDB.com ID of the facility. - :type peering_db_facility_id: int - :param peering_db_facility_link: The PeeringDB.com URL of the facility. - :type peering_db_facility_link: str + :ivar address: The address of the direct peering facility. + :vartype address: str + :ivar direct_peering_type: The type of the direct peering. Known values are: "Edge", "Transit", + "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". + :vartype direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType + :ivar peering_db_facility_id: The PeeringDB.com ID of the facility. + :vartype peering_db_facility_id: int + :ivar peering_db_facility_link: The PeeringDB.com URL of the facility. + :vartype peering_db_facility_link: str """ _attribute_map = { - 'address': {'key': 'address', 'type': 'str'}, - 'direct_peering_type': {'key': 'directPeeringType', 'type': 'str'}, - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'peering_db_facility_link': {'key': 'peeringDBFacilityLink', 'type': 'str'}, + "address": {"key": "address", "type": "str"}, + "direct_peering_type": {"key": "directPeeringType", "type": "str"}, + "peering_db_facility_id": {"key": "peeringDBFacilityId", "type": "int"}, + "peering_db_facility_link": {"key": "peeringDBFacilityLink", "type": "str"}, } def __init__( self, *, address: Optional[str] = None, - direct_peering_type: Optional[Union[str, "DirectPeeringType"]] = None, + direct_peering_type: Optional[Union[str, "_models.DirectPeeringType"]] = None, peering_db_facility_id: Optional[int] = None, peering_db_facility_link: Optional[str] = None, **kwargs ): - super(DirectPeeringFacility, self).__init__(**kwargs) + """ + :keyword address: The address of the direct peering facility. + :paramtype address: str + :keyword direct_peering_type: The type of the direct peering. Known values are: "Edge", + "Transit", "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". + :paramtype direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType + :keyword peering_db_facility_id: The PeeringDB.com ID of the facility. + :paramtype peering_db_facility_id: int + :keyword peering_db_facility_link: The PeeringDB.com URL of the facility. + :paramtype peering_db_facility_link: str + """ + super().__init__(**kwargs) self.address = address self.direct_peering_type = direct_peering_type self.peering_db_facility_id = peering_db_facility_id self.peering_db_facility_link = peering_db_facility_link -class ErrorResponse(msrest.serialization.Model): - """The error response that indicates why an operation has failed. +class ErrorDetail(_serialization.Model): + """The error detail that describes why an operation has failed. Variables are only populated by the server, and will be ignored when sending a request. @@ -263,99 +576,132 @@ class ErrorResponse(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None -class ExchangeConnection(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): + """The error response that indicates why an operation has failed. + + :ivar error: The error detail that describes why an operation has failed. + :vartype error: ~azure.mgmt.peering.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error detail that describes why an operation has failed. + :paramtype error: ~azure.mgmt.peering.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class ExchangeConnection(_serialization.Model): """The properties that define an exchange connection. Variables are only populated by the server, and will be ignored when sending a request. - :param peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection has + :ivar peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection has to be set up. - :type peering_db_facility_id: int - :ivar connection_state: The state of the connection. Possible values include: "None", + :vartype peering_db_facility_id: int + :ivar connection_state: The state of the connection. Known values are: "None", "PendingApproval", "Approved", "ProvisioningStarted", "ProvisioningFailed", - "ProvisioningCompleted", "Validating", "Active". + "ProvisioningCompleted", "Validating", "Active", "TypeChangeRequested", and + "TypeChangeInProgress". :vartype connection_state: str or ~azure.mgmt.peering.models.ConnectionState - :param bgp_session: The BGP session associated with the connection. - :type bgp_session: ~azure.mgmt.peering.models.BgpSession - :param connection_identifier: The unique identifier (GUID) for the connection. - :type connection_identifier: str + :ivar bgp_session: The BGP session associated with the connection. + :vartype bgp_session: ~azure.mgmt.peering.models.BgpSession + :ivar connection_identifier: The unique identifier (GUID) for the connection. + :vartype connection_identifier: str + :ivar error_message: The error message related to the connection state, if any. + :vartype error_message: str """ _validation = { - 'connection_state': {'readonly': True}, + "connection_state": {"readonly": True}, + "error_message": {"readonly": True}, } _attribute_map = { - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'connection_state': {'key': 'connectionState', 'type': 'str'}, - 'bgp_session': {'key': 'bgpSession', 'type': 'BgpSession'}, - 'connection_identifier': {'key': 'connectionIdentifier', 'type': 'str'}, + "peering_db_facility_id": {"key": "peeringDBFacilityId", "type": "int"}, + "connection_state": {"key": "connectionState", "type": "str"}, + "bgp_session": {"key": "bgpSession", "type": "BgpSession"}, + "connection_identifier": {"key": "connectionIdentifier", "type": "str"}, + "error_message": {"key": "errorMessage", "type": "str"}, } def __init__( self, *, peering_db_facility_id: Optional[int] = None, - bgp_session: Optional["BgpSession"] = None, + bgp_session: Optional["_models.BgpSession"] = None, connection_identifier: Optional[str] = None, **kwargs ): - super(ExchangeConnection, self).__init__(**kwargs) + """ + :keyword peering_db_facility_id: The PeeringDB.com ID of the facility at which the connection + has to be set up. + :paramtype peering_db_facility_id: int + :keyword bgp_session: The BGP session associated with the connection. + :paramtype bgp_session: ~azure.mgmt.peering.models.BgpSession + :keyword connection_identifier: The unique identifier (GUID) for the connection. + :paramtype connection_identifier: str + """ + super().__init__(**kwargs) self.peering_db_facility_id = peering_db_facility_id self.connection_state = None self.bgp_session = bgp_session self.connection_identifier = connection_identifier + self.error_message = None -class ExchangePeeringFacility(msrest.serialization.Model): +class ExchangePeeringFacility(_serialization.Model): """The properties that define an exchange peering facility. - :param exchange_name: The name of the exchange peering facility. - :type exchange_name: str - :param bandwidth_in_mbps: The bandwidth of the connection between Microsoft and the exchange + :ivar exchange_name: The name of the exchange peering facility. + :vartype exchange_name: str + :ivar bandwidth_in_mbps: The bandwidth of the connection between Microsoft and the exchange peering facility. - :type bandwidth_in_mbps: int - :param microsoft_i_pv4_address: The IPv4 address of Microsoft at the exchange peering facility. - :type microsoft_i_pv4_address: str - :param microsoft_i_pv6_address: The IPv6 address of Microsoft at the exchange peering facility. - :type microsoft_i_pv6_address: str - :param facility_i_pv4_prefix: The IPv4 prefixes associated with the exchange peering facility. - :type facility_i_pv4_prefix: str - :param facility_i_pv6_prefix: The IPv6 prefixes associated with the exchange peering facility. - :type facility_i_pv6_prefix: str - :param peering_db_facility_id: The PeeringDB.com ID of the facility. - :type peering_db_facility_id: int - :param peering_db_facility_link: The PeeringDB.com URL of the facility. - :type peering_db_facility_link: str + :vartype bandwidth_in_mbps: int + :ivar microsoft_i_pv4_address: The IPv4 address of Microsoft at the exchange peering facility. + :vartype microsoft_i_pv4_address: str + :ivar microsoft_i_pv6_address: The IPv6 address of Microsoft at the exchange peering facility. + :vartype microsoft_i_pv6_address: str + :ivar facility_i_pv4_prefix: The IPv4 prefixes associated with the exchange peering facility. + :vartype facility_i_pv4_prefix: str + :ivar facility_i_pv6_prefix: The IPv6 prefixes associated with the exchange peering facility. + :vartype facility_i_pv6_prefix: str + :ivar peering_db_facility_id: The PeeringDB.com ID of the facility. + :vartype peering_db_facility_id: int + :ivar peering_db_facility_link: The PeeringDB.com URL of the facility. + :vartype peering_db_facility_link: str """ _attribute_map = { - 'exchange_name': {'key': 'exchangeName', 'type': 'str'}, - 'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'}, - 'microsoft_i_pv4_address': {'key': 'microsoftIPv4Address', 'type': 'str'}, - 'microsoft_i_pv6_address': {'key': 'microsoftIPv6Address', 'type': 'str'}, - 'facility_i_pv4_prefix': {'key': 'facilityIPv4Prefix', 'type': 'str'}, - 'facility_i_pv6_prefix': {'key': 'facilityIPv6Prefix', 'type': 'str'}, - 'peering_db_facility_id': {'key': 'peeringDBFacilityId', 'type': 'int'}, - 'peering_db_facility_link': {'key': 'peeringDBFacilityLink', 'type': 'str'}, + "exchange_name": {"key": "exchangeName", "type": "str"}, + "bandwidth_in_mbps": {"key": "bandwidthInMbps", "type": "int"}, + "microsoft_i_pv4_address": {"key": "microsoftIPv4Address", "type": "str"}, + "microsoft_i_pv6_address": {"key": "microsoftIPv6Address", "type": "str"}, + "facility_i_pv4_prefix": {"key": "facilityIPv4Prefix", "type": "str"}, + "facility_i_pv6_prefix": {"key": "facilityIPv6Prefix", "type": "str"}, + "peering_db_facility_id": {"key": "peeringDBFacilityId", "type": "int"}, + "peering_db_facility_link": {"key": "peeringDBFacilityLink", "type": "str"}, } def __init__( @@ -371,7 +717,30 @@ def __init__( peering_db_facility_link: Optional[str] = None, **kwargs ): - super(ExchangePeeringFacility, self).__init__(**kwargs) + """ + :keyword exchange_name: The name of the exchange peering facility. + :paramtype exchange_name: str + :keyword bandwidth_in_mbps: The bandwidth of the connection between Microsoft and the exchange + peering facility. + :paramtype bandwidth_in_mbps: int + :keyword microsoft_i_pv4_address: The IPv4 address of Microsoft at the exchange peering + facility. + :paramtype microsoft_i_pv4_address: str + :keyword microsoft_i_pv6_address: The IPv6 address of Microsoft at the exchange peering + facility. + :paramtype microsoft_i_pv6_address: str + :keyword facility_i_pv4_prefix: The IPv4 prefixes associated with the exchange peering + facility. + :paramtype facility_i_pv4_prefix: str + :keyword facility_i_pv6_prefix: The IPv6 prefixes associated with the exchange peering + facility. + :paramtype facility_i_pv6_prefix: str + :keyword peering_db_facility_id: The PeeringDB.com ID of the facility. + :paramtype peering_db_facility_id: int + :keyword peering_db_facility_link: The PeeringDB.com URL of the facility. + :paramtype peering_db_facility_link: str + """ + super().__init__(**kwargs) self.exchange_name = exchange_name self.bandwidth_in_mbps = bandwidth_in_mbps self.microsoft_i_pv4_address = microsoft_i_pv4_address @@ -382,7 +751,150 @@ def __init__( self.peering_db_facility_link = peering_db_facility_link -class Operation(msrest.serialization.Model): +class LogAnalyticsWorkspaceProperties(_serialization.Model): + """The properties that define a Log Analytics Workspace. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar workspace_id: The Workspace ID. + :vartype workspace_id: str + :ivar key: The Workspace Key. + :vartype key: str + :ivar connected_agents: The list of connected agents. + :vartype connected_agents: list[str] + """ + + _validation = { + "workspace_id": {"readonly": True}, + "key": {"readonly": True}, + "connected_agents": {"readonly": True}, + } + + _attribute_map = { + "workspace_id": {"key": "workspaceID", "type": "str"}, + "key": {"key": "key", "type": "str"}, + "connected_agents": {"key": "connectedAgents", "type": "[str]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.workspace_id = None + self.key = None + self.connected_agents = None + + +class LookingGlassOutput(_serialization.Model): + """Looking glass output model. + + :ivar command: Invoked command. Known values are: "Traceroute", "Ping", and "BgpRoute". + :vartype command: str or ~azure.mgmt.peering.models.Command + :ivar output: Output of the command. + :vartype output: str + """ + + _attribute_map = { + "command": {"key": "command", "type": "str"}, + "output": {"key": "output", "type": "str"}, + } + + def __init__( + self, *, command: Optional[Union[str, "_models.Command"]] = None, output: Optional[str] = None, **kwargs + ): + """ + :keyword command: Invoked command. Known values are: "Traceroute", "Ping", and "BgpRoute". + :paramtype command: str or ~azure.mgmt.peering.models.Command + :keyword output: Output of the command. + :paramtype output: str + """ + super().__init__(**kwargs) + self.command = command + self.output = output + + +class MetricDimension(_serialization.Model): + """Dimensions of the metric. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Name of the dimension. + :vartype name: str + :ivar display_name: Localized friendly display name of the dimension. + :vartype display_name: str + """ + + _validation = { + "name": {"readonly": True}, + "display_name": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.name = None + self.display_name = None + + +class MetricSpecification(_serialization.Model): + """Specifications of the Metrics for Azure Monitoring. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Name of the metric. + :vartype name: str + :ivar display_name: Localized friendly display name of the metric. + :vartype display_name: str + :ivar display_description: Localized friendly description of the metric. + :vartype display_description: str + :ivar unit: Unit that makes sense for the metric. + :vartype unit: str + :ivar aggregation_type: Aggregation type will be set to one of the values: Average, Minimum, + Maximum, Total, Count. + :vartype aggregation_type: str + :ivar supported_time_grain_types: Supported time grain types for the metric. + :vartype supported_time_grain_types: list[str] + :ivar dimensions: Dimensions of the metric. + :vartype dimensions: list[~azure.mgmt.peering.models.MetricDimension] + """ + + _validation = { + "name": {"readonly": True}, + "display_name": {"readonly": True}, + "display_description": {"readonly": True}, + "unit": {"readonly": True}, + "aggregation_type": {"readonly": True}, + "supported_time_grain_types": {"readonly": True}, + "dimensions": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "display_description": {"key": "displayDescription", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "aggregation_type": {"key": "aggregationType", "type": "str"}, + "supported_time_grain_types": {"key": "supportedTimeGrainTypes", "type": "[str]"}, + "dimensions": {"key": "dimensions", "type": "[MetricDimension]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.name = None + self.display_name = None + self.display_description = None + self.unit = None + self.aggregation_type = None + self.supported_time_grain_types = None + self.dimensions = None + + +class Operation(_serialization.Model): """The peering API operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -393,31 +905,34 @@ class Operation(msrest.serialization.Model): :vartype display: ~azure.mgmt.peering.models.OperationDisplayInfo :ivar is_data_action: The flag that indicates whether the operation applies to data plane. :vartype is_data_action: bool + :ivar service_specification: Service specification payload. + :vartype service_specification: ~azure.mgmt.peering.models.ServiceSpecification """ _validation = { - 'name': {'readonly': True}, - 'display': {'readonly': True}, - 'is_data_action': {'readonly': True}, + "name": {"readonly": True}, + "display": {"readonly": True}, + "is_data_action": {"readonly": True}, + "service_specification": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplayInfo'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplayInfo"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "service_specification": {"key": "properties.serviceSpecification", "type": "ServiceSpecification"}, } - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.display = None self.is_data_action = None + self.service_specification = None -class OperationDisplayInfo(msrest.serialization.Model): +class OperationDisplayInfo(_serialization.Model): """The information related to the operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -433,91 +948,54 @@ class OperationDisplayInfo(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationDisplayInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """The paginated list of peering API operations. - :param value: The list of peering API operations. - :type value: list[~azure.mgmt.peering.models.Operation] - :param next_link: The link to fetch the next page of peering API operations. - :type next_link: str + :ivar value: The list of peering API operations. + :vartype value: list[~azure.mgmt.peering.models.Operation] + :ivar next_link: The link to fetch the next page of peering API operations. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Operation"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The list of peering API operations. + :paramtype value: list[~azure.mgmt.peering.models.Operation] + :keyword next_link: The link to fetch the next page of peering API operations. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class Resource(msrest.serialization.Model): - """The ARM resource class. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the resource. - :vartype name: str - :ivar id: The ID of the resource. - :vartype id: str - :ivar type: The type of the resource. - :vartype type: str - """ - - _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.name = None - self.id = None - self.type = None - - class PeerAsn(Resource): """The essential information related to the peer's ASN. @@ -529,76 +1007,89 @@ class PeerAsn(Resource): :vartype id: str :ivar type: The type of the resource. :vartype type: str - :param peer_asn: The Autonomous System Number (ASN) of the peer. - :type peer_asn: int - :param peer_contact_info: The contact information of the peer. - :type peer_contact_info: ~azure.mgmt.peering.models.ContactInfo - :param peer_name: The name of the peer. - :type peer_name: str - :param validation_state: The validation state of the ASN associated with the peer. Possible - values include: "None", "Pending", "Approved", "Failed". - :type validation_state: str or ~azure.mgmt.peering.models.ValidationState + :ivar peer_asn: The Autonomous System Number (ASN) of the peer. + :vartype peer_asn: int + :ivar peer_contact_detail: The contact details of the peer. + :vartype peer_contact_detail: list[~azure.mgmt.peering.models.ContactDetail] + :ivar peer_name: The name of the peer. + :vartype peer_name: str + :ivar validation_state: The validation state of the ASN associated with the peer. Known values + are: "None", "Pending", "Approved", and "Failed". + :vartype validation_state: str or ~azure.mgmt.peering.models.ValidationState + :ivar error_message: The error message for the validation state. + :vartype error_message: str """ _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "validation_state": {"readonly": True}, + "error_message": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'peer_asn': {'key': 'properties.peerAsn', 'type': 'int'}, - 'peer_contact_info': {'key': 'properties.peerContactInfo', 'type': 'ContactInfo'}, - 'peer_name': {'key': 'properties.peerName', 'type': 'str'}, - 'validation_state': {'key': 'properties.validationState', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "peer_asn": {"key": "properties.peerAsn", "type": "int"}, + "peer_contact_detail": {"key": "properties.peerContactDetail", "type": "[ContactDetail]"}, + "peer_name": {"key": "properties.peerName", "type": "str"}, + "validation_state": {"key": "properties.validationState", "type": "str"}, + "error_message": {"key": "properties.errorMessage", "type": "str"}, } def __init__( self, *, peer_asn: Optional[int] = None, - peer_contact_info: Optional["ContactInfo"] = None, + peer_contact_detail: Optional[List["_models.ContactDetail"]] = None, peer_name: Optional[str] = None, - validation_state: Optional[Union[str, "ValidationState"]] = None, **kwargs ): - super(PeerAsn, self).__init__(**kwargs) + """ + :keyword peer_asn: The Autonomous System Number (ASN) of the peer. + :paramtype peer_asn: int + :keyword peer_contact_detail: The contact details of the peer. + :paramtype peer_contact_detail: list[~azure.mgmt.peering.models.ContactDetail] + :keyword peer_name: The name of the peer. + :paramtype peer_name: str + """ + super().__init__(**kwargs) self.peer_asn = peer_asn - self.peer_contact_info = peer_contact_info + self.peer_contact_detail = peer_contact_detail self.peer_name = peer_name - self.validation_state = validation_state + self.validation_state = None + self.error_message = None -class PeerAsnListResult(msrest.serialization.Model): +class PeerAsnListResult(_serialization.Model): """The paginated list of peer ASNs. - :param value: The list of peer ASNs. - :type value: list[~azure.mgmt.peering.models.PeerAsn] - :param next_link: The link to fetch the next page of peer ASNs. - :type next_link: str + :ivar value: The list of peer ASNs. + :vartype value: list[~azure.mgmt.peering.models.PeerAsn] + :ivar next_link: The link to fetch the next page of peer ASNs. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PeerAsn]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PeerAsn]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["PeerAsn"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(PeerAsnListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.PeerAsn"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The list of peer ASNs. + :paramtype value: list[~azure.mgmt.peering.models.PeerAsn] + :keyword next_link: The link to fetch the next page of peer ASNs. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class Peering(Resource): +class Peering(Resource): # pylint: disable=too-many-instance-attributes """Peering is a logical representation of a set of connections to the Microsoft Cloud Edge at a location. Variables are only populated by the server, and will be ignored when sending a request. @@ -611,62 +1102,78 @@ class Peering(Resource): :vartype id: str :ivar type: The type of the resource. :vartype type: str - :param sku: Required. The SKU that defines the tier and kind of the peering. - :type sku: ~azure.mgmt.peering.models.PeeringSku - :param kind: Required. The kind of the peering. Possible values include: "Direct", "Exchange". - :type kind: str or ~azure.mgmt.peering.models.Kind - :param location: Required. The location of the resource. - :type location: str - :param tags: A set of tags. The resource tags. - :type tags: dict[str, str] - :param direct: The properties that define a direct peering. - :type direct: ~azure.mgmt.peering.models.PeeringPropertiesDirect - :param exchange: The properties that define an exchange peering. - :type exchange: ~azure.mgmt.peering.models.PeeringPropertiesExchange - :param peering_location: The location of the peering. - :type peering_location: str - :ivar provisioning_state: The provisioning state of the resource. Possible values include: - "Succeeded", "Updating", "Deleting", "Failed". + :ivar sku: The SKU that defines the tier and kind of the peering. Required. + :vartype sku: ~azure.mgmt.peering.models.PeeringSku + :ivar kind: The kind of the peering. Required. Known values are: "Direct" and "Exchange". + :vartype kind: str or ~azure.mgmt.peering.models.Kind + :ivar location: The location of the resource. Required. + :vartype location: str + :ivar tags: The resource tags. + :vartype tags: dict[str, str] + :ivar direct: The properties that define a direct peering. + :vartype direct: ~azure.mgmt.peering.models.PeeringPropertiesDirect + :ivar exchange: The properties that define an exchange peering. + :vartype exchange: ~azure.mgmt.peering.models.PeeringPropertiesExchange + :ivar peering_location: The location of the peering. + :vartype peering_location: str + :ivar provisioning_state: The provisioning state of the resource. Known values are: + "Succeeded", "Updating", "Deleting", and "Failed". :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState """ _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'sku': {'required': True}, - 'kind': {'required': True}, - 'location': {'required': True}, - 'provisioning_state': {'readonly': True}, + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "sku": {"required": True}, + "kind": {"required": True}, + "location": {"required": True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'PeeringSku'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'direct': {'key': 'properties.direct', 'type': 'PeeringPropertiesDirect'}, - 'exchange': {'key': 'properties.exchange', 'type': 'PeeringPropertiesExchange'}, - 'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "sku": {"key": "sku", "type": "PeeringSku"}, + "kind": {"key": "kind", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "direct": {"key": "properties.direct", "type": "PeeringPropertiesDirect"}, + "exchange": {"key": "properties.exchange", "type": "PeeringPropertiesExchange"}, + "peering_location": {"key": "properties.peeringLocation", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } def __init__( self, *, - sku: "PeeringSku", - kind: Union[str, "Kind"], + sku: "_models.PeeringSku", + kind: Union[str, "_models.Kind"], location: str, tags: Optional[Dict[str, str]] = None, - direct: Optional["PeeringPropertiesDirect"] = None, - exchange: Optional["PeeringPropertiesExchange"] = None, + direct: Optional["_models.PeeringPropertiesDirect"] = None, + exchange: Optional["_models.PeeringPropertiesExchange"] = None, peering_location: Optional[str] = None, **kwargs ): - super(Peering, self).__init__(**kwargs) + """ + :keyword sku: The SKU that defines the tier and kind of the peering. Required. + :paramtype sku: ~azure.mgmt.peering.models.PeeringSku + :keyword kind: The kind of the peering. Required. Known values are: "Direct" and "Exchange". + :paramtype kind: str or ~azure.mgmt.peering.models.Kind + :keyword location: The location of the resource. Required. + :paramtype location: str + :keyword tags: The resource tags. + :paramtype tags: dict[str, str] + :keyword direct: The properties that define a direct peering. + :paramtype direct: ~azure.mgmt.peering.models.PeeringPropertiesDirect + :keyword exchange: The properties that define an exchange peering. + :paramtype exchange: ~azure.mgmt.peering.models.PeeringPropertiesExchange + :keyword peering_location: The location of the peering. + :paramtype peering_location: str + """ + super().__init__(**kwargs) self.sku = sku self.kind = kind self.location = location @@ -677,54 +1184,54 @@ def __init__( self.provisioning_state = None -class PeeringBandwidthOffer(msrest.serialization.Model): +class PeeringBandwidthOffer(_serialization.Model): """The properties that define a peering bandwidth offer. - :param offer_name: The name of the bandwidth offer. - :type offer_name: str - :param value_in_mbps: The value of the bandwidth offer in Mbps. - :type value_in_mbps: int + :ivar offer_name: The name of the bandwidth offer. + :vartype offer_name: str + :ivar value_in_mbps: The value of the bandwidth offer in Mbps. + :vartype value_in_mbps: int """ _attribute_map = { - 'offer_name': {'key': 'offerName', 'type': 'str'}, - 'value_in_mbps': {'key': 'valueInMbps', 'type': 'int'}, + "offer_name": {"key": "offerName", "type": "str"}, + "value_in_mbps": {"key": "valueInMbps", "type": "int"}, } - def __init__( - self, - *, - offer_name: Optional[str] = None, - value_in_mbps: Optional[int] = None, - **kwargs - ): - super(PeeringBandwidthOffer, self).__init__(**kwargs) + def __init__(self, *, offer_name: Optional[str] = None, value_in_mbps: Optional[int] = None, **kwargs): + """ + :keyword offer_name: The name of the bandwidth offer. + :paramtype offer_name: str + :keyword value_in_mbps: The value of the bandwidth offer in Mbps. + :paramtype value_in_mbps: int + """ + super().__init__(**kwargs) self.offer_name = offer_name self.value_in_mbps = value_in_mbps -class PeeringListResult(msrest.serialization.Model): +class PeeringListResult(_serialization.Model): """The paginated list of peerings. - :param value: The list of peerings. - :type value: list[~azure.mgmt.peering.models.Peering] - :param next_link: The link to fetch the next page of peerings. - :type next_link: str + :ivar value: The list of peerings. + :vartype value: list[~azure.mgmt.peering.models.Peering] + :ivar next_link: The link to fetch the next page of peerings. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Peering]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Peering]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["Peering"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - super(PeeringListResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.Peering"]] = None, next_link: Optional[str] = None, **kwargs): + """ + :keyword value: The list of peerings. + :paramtype value: list[~azure.mgmt.peering.models.Peering] + :keyword next_link: The link to fetch the next page of peerings. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -740,51 +1247,66 @@ class PeeringLocation(Resource): :vartype id: str :ivar type: The type of the resource. :vartype type: str - :param kind: The kind of peering that the peering location supports. Possible values include: - "Direct", "Exchange". - :type kind: str or ~azure.mgmt.peering.models.Kind - :param direct: The properties that define a direct peering location. - :type direct: ~azure.mgmt.peering.models.PeeringLocationPropertiesDirect - :param exchange: The properties that define an exchange peering location. - :type exchange: ~azure.mgmt.peering.models.PeeringLocationPropertiesExchange - :param peering_location: The name of the peering location. - :type peering_location: str - :param country: The country in which the peering location exists. - :type country: str - :param azure_region: The Azure region associated with the peering location. - :type azure_region: str + :ivar kind: The kind of peering that the peering location supports. Known values are: "Direct" + and "Exchange". + :vartype kind: str or ~azure.mgmt.peering.models.Kind + :ivar direct: The properties that define a direct peering location. + :vartype direct: ~azure.mgmt.peering.models.PeeringLocationPropertiesDirect + :ivar exchange: The properties that define an exchange peering location. + :vartype exchange: ~azure.mgmt.peering.models.PeeringLocationPropertiesExchange + :ivar peering_location: The name of the peering location. + :vartype peering_location: str + :ivar country: The country in which the peering location exists. + :vartype country: str + :ivar azure_region: The Azure region associated with the peering location. + :vartype azure_region: str """ _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'direct': {'key': 'properties.direct', 'type': 'PeeringLocationPropertiesDirect'}, - 'exchange': {'key': 'properties.exchange', 'type': 'PeeringLocationPropertiesExchange'}, - 'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'}, - 'country': {'key': 'properties.country', 'type': 'str'}, - 'azure_region': {'key': 'properties.azureRegion', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "direct": {"key": "properties.direct", "type": "PeeringLocationPropertiesDirect"}, + "exchange": {"key": "properties.exchange", "type": "PeeringLocationPropertiesExchange"}, + "peering_location": {"key": "properties.peeringLocation", "type": "str"}, + "country": {"key": "properties.country", "type": "str"}, + "azure_region": {"key": "properties.azureRegion", "type": "str"}, } def __init__( self, *, - kind: Optional[Union[str, "Kind"]] = None, - direct: Optional["PeeringLocationPropertiesDirect"] = None, - exchange: Optional["PeeringLocationPropertiesExchange"] = None, + kind: Optional[Union[str, "_models.Kind"]] = None, + direct: Optional["_models.PeeringLocationPropertiesDirect"] = None, + exchange: Optional["_models.PeeringLocationPropertiesExchange"] = None, peering_location: Optional[str] = None, country: Optional[str] = None, azure_region: Optional[str] = None, **kwargs ): - super(PeeringLocation, self).__init__(**kwargs) + """ + :keyword kind: The kind of peering that the peering location supports. Known values are: + "Direct" and "Exchange". + :paramtype kind: str or ~azure.mgmt.peering.models.Kind + :keyword direct: The properties that define a direct peering location. + :paramtype direct: ~azure.mgmt.peering.models.PeeringLocationPropertiesDirect + :keyword exchange: The properties that define an exchange peering location. + :paramtype exchange: ~azure.mgmt.peering.models.PeeringLocationPropertiesExchange + :keyword peering_location: The name of the peering location. + :paramtype peering_location: str + :keyword country: The country in which the peering location exists. + :paramtype country: str + :keyword azure_region: The Azure region associated with the peering location. + :paramtype azure_region: str + """ + super().__init__(**kwargs) self.kind = kind self.direct = direct self.exchange = exchange @@ -793,144 +1315,423 @@ def __init__( self.azure_region = azure_region -class PeeringLocationListResult(msrest.serialization.Model): +class PeeringLocationListResult(_serialization.Model): """The paginated list of peering locations. - :param value: The list of peering locations. - :type value: list[~azure.mgmt.peering.models.PeeringLocation] - :param next_link: The link to fetch the next page of peering locations. - :type next_link: str + :ivar value: The list of peering locations. + :vartype value: list[~azure.mgmt.peering.models.PeeringLocation] + :ivar next_link: The link to fetch the next page of peering locations. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringLocation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PeeringLocation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["PeeringLocation"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.PeeringLocation"]] = None, next_link: Optional[str] = None, **kwargs ): - super(PeeringLocationListResult, self).__init__(**kwargs) + """ + :keyword value: The list of peering locations. + :paramtype value: list[~azure.mgmt.peering.models.PeeringLocation] + :keyword next_link: The link to fetch the next page of peering locations. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class PeeringLocationPropertiesDirect(msrest.serialization.Model): +class PeeringLocationPropertiesDirect(_serialization.Model): """The properties that define a direct peering location. - :param peering_facilities: The list of direct peering facilities at the peering location. - :type peering_facilities: list[~azure.mgmt.peering.models.DirectPeeringFacility] - :param bandwidth_offers: The list of bandwidth offers available at the peering location. - :type bandwidth_offers: list[~azure.mgmt.peering.models.PeeringBandwidthOffer] + :ivar peering_facilities: The list of direct peering facilities at the peering location. + :vartype peering_facilities: list[~azure.mgmt.peering.models.DirectPeeringFacility] + :ivar bandwidth_offers: The list of bandwidth offers available at the peering location. + :vartype bandwidth_offers: list[~azure.mgmt.peering.models.PeeringBandwidthOffer] """ _attribute_map = { - 'peering_facilities': {'key': 'peeringFacilities', 'type': '[DirectPeeringFacility]'}, - 'bandwidth_offers': {'key': 'bandwidthOffers', 'type': '[PeeringBandwidthOffer]'}, + "peering_facilities": {"key": "peeringFacilities", "type": "[DirectPeeringFacility]"}, + "bandwidth_offers": {"key": "bandwidthOffers", "type": "[PeeringBandwidthOffer]"}, } def __init__( self, *, - peering_facilities: Optional[List["DirectPeeringFacility"]] = None, - bandwidth_offers: Optional[List["PeeringBandwidthOffer"]] = None, + peering_facilities: Optional[List["_models.DirectPeeringFacility"]] = None, + bandwidth_offers: Optional[List["_models.PeeringBandwidthOffer"]] = None, **kwargs ): - super(PeeringLocationPropertiesDirect, self).__init__(**kwargs) + """ + :keyword peering_facilities: The list of direct peering facilities at the peering location. + :paramtype peering_facilities: list[~azure.mgmt.peering.models.DirectPeeringFacility] + :keyword bandwidth_offers: The list of bandwidth offers available at the peering location. + :paramtype bandwidth_offers: list[~azure.mgmt.peering.models.PeeringBandwidthOffer] + """ + super().__init__(**kwargs) self.peering_facilities = peering_facilities self.bandwidth_offers = bandwidth_offers -class PeeringLocationPropertiesExchange(msrest.serialization.Model): +class PeeringLocationPropertiesExchange(_serialization.Model): """The properties that define an exchange peering location. - :param peering_facilities: The list of exchange peering facilities at the peering location. - :type peering_facilities: list[~azure.mgmt.peering.models.ExchangePeeringFacility] + :ivar peering_facilities: The list of exchange peering facilities at the peering location. + :vartype peering_facilities: list[~azure.mgmt.peering.models.ExchangePeeringFacility] """ _attribute_map = { - 'peering_facilities': {'key': 'peeringFacilities', 'type': '[ExchangePeeringFacility]'}, + "peering_facilities": {"key": "peeringFacilities", "type": "[ExchangePeeringFacility]"}, } - def __init__( - self, - *, - peering_facilities: Optional[List["ExchangePeeringFacility"]] = None, - **kwargs - ): - super(PeeringLocationPropertiesExchange, self).__init__(**kwargs) + def __init__(self, *, peering_facilities: Optional[List["_models.ExchangePeeringFacility"]] = None, **kwargs): + """ + :keyword peering_facilities: The list of exchange peering facilities at the peering location. + :paramtype peering_facilities: list[~azure.mgmt.peering.models.ExchangePeeringFacility] + """ + super().__init__(**kwargs) self.peering_facilities = peering_facilities -class PeeringPropertiesDirect(msrest.serialization.Model): +class PeeringPropertiesDirect(_serialization.Model): """The properties that define a direct peering. - :param connections: The set of connections that constitute a direct peering. - :type connections: list[~azure.mgmt.peering.models.DirectConnection] - :param use_for_peering_service: The flag that indicates whether or not the peering is used for + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar connections: The set of connections that constitute a direct peering. + :vartype connections: list[~azure.mgmt.peering.models.DirectConnection] + :ivar use_for_peering_service: The flag that indicates whether or not the peering is used for peering service. - :type use_for_peering_service: bool - :param peer_asn: The reference of the peer ASN. - :type peer_asn: ~azure.mgmt.peering.models.SubResource - :param direct_peering_type: The type of direct peering. Possible values include: "Edge", - "Transit", "Cdn", "Internal". - :type direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType + :vartype use_for_peering_service: bool + :ivar peer_asn: The reference of the peer ASN. + :vartype peer_asn: ~azure.mgmt.peering.models.SubResource + :ivar direct_peering_type: The type of direct peering. Known values are: "Edge", "Transit", + "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". + :vartype direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType """ + _validation = { + "use_for_peering_service": {"readonly": True}, + } + _attribute_map = { - 'connections': {'key': 'connections', 'type': '[DirectConnection]'}, - 'use_for_peering_service': {'key': 'useForPeeringService', 'type': 'bool'}, - 'peer_asn': {'key': 'peerAsn', 'type': 'SubResource'}, - 'direct_peering_type': {'key': 'directPeeringType', 'type': 'str'}, + "connections": {"key": "connections", "type": "[DirectConnection]"}, + "use_for_peering_service": {"key": "useForPeeringService", "type": "bool"}, + "peer_asn": {"key": "peerAsn", "type": "SubResource"}, + "direct_peering_type": {"key": "directPeeringType", "type": "str"}, } def __init__( self, *, - connections: Optional[List["DirectConnection"]] = None, - use_for_peering_service: Optional[bool] = None, - peer_asn: Optional["SubResource"] = None, - direct_peering_type: Optional[Union[str, "DirectPeeringType"]] = None, + connections: Optional[List["_models.DirectConnection"]] = None, + peer_asn: Optional["_models.SubResource"] = None, + direct_peering_type: Optional[Union[str, "_models.DirectPeeringType"]] = None, **kwargs ): - super(PeeringPropertiesDirect, self).__init__(**kwargs) + """ + :keyword connections: The set of connections that constitute a direct peering. + :paramtype connections: list[~azure.mgmt.peering.models.DirectConnection] + :keyword peer_asn: The reference of the peer ASN. + :paramtype peer_asn: ~azure.mgmt.peering.models.SubResource + :keyword direct_peering_type: The type of direct peering. Known values are: "Edge", "Transit", + "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". + :paramtype direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType + """ + super().__init__(**kwargs) self.connections = connections - self.use_for_peering_service = use_for_peering_service + self.use_for_peering_service = None self.peer_asn = peer_asn self.direct_peering_type = direct_peering_type -class PeeringPropertiesExchange(msrest.serialization.Model): +class PeeringPropertiesExchange(_serialization.Model): """The properties that define an exchange peering. - :param connections: The set of connections that constitute an exchange peering. - :type connections: list[~azure.mgmt.peering.models.ExchangeConnection] - :param peer_asn: The reference of the peer ASN. - :type peer_asn: ~azure.mgmt.peering.models.SubResource + :ivar connections: The set of connections that constitute an exchange peering. + :vartype connections: list[~azure.mgmt.peering.models.ExchangeConnection] + :ivar peer_asn: The reference of the peer ASN. + :vartype peer_asn: ~azure.mgmt.peering.models.SubResource """ _attribute_map = { - 'connections': {'key': 'connections', 'type': '[ExchangeConnection]'}, - 'peer_asn': {'key': 'peerAsn', 'type': 'SubResource'}, + "connections": {"key": "connections", "type": "[ExchangeConnection]"}, + "peer_asn": {"key": "peerAsn", "type": "SubResource"}, } def __init__( self, *, - connections: Optional[List["ExchangeConnection"]] = None, - peer_asn: Optional["SubResource"] = None, + connections: Optional[List["_models.ExchangeConnection"]] = None, + peer_asn: Optional["_models.SubResource"] = None, **kwargs ): - super(PeeringPropertiesExchange, self).__init__(**kwargs) + """ + :keyword connections: The set of connections that constitute an exchange peering. + :paramtype connections: list[~azure.mgmt.peering.models.ExchangeConnection] + :keyword peer_asn: The reference of the peer ASN. + :paramtype peer_asn: ~azure.mgmt.peering.models.SubResource + """ + super().__init__(**kwargs) self.connections = connections self.peer_asn = peer_asn -class PeeringService(Resource): +class PeeringReceivedRoute(_serialization.Model): + """The properties that define a received route. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar prefix: The prefix. + :vartype prefix: str + :ivar next_hop: The next hop for the prefix. + :vartype next_hop: str + :ivar as_path: The AS path for the prefix. + :vartype as_path: str + :ivar origin_as_validation_state: The origin AS change information for the prefix. + :vartype origin_as_validation_state: str + :ivar rpki_validation_state: The RPKI validation state for the prefix and origin AS that's + listed in the AS path. + :vartype rpki_validation_state: str + :ivar trust_anchor: The authority which holds the Route Origin Authorization record for the + prefix, if any. + :vartype trust_anchor: str + :ivar received_timestamp: The received timestamp associated with the prefix. + :vartype received_timestamp: str + """ + + _validation = { + "prefix": {"readonly": True}, + "next_hop": {"readonly": True}, + "as_path": {"readonly": True}, + "origin_as_validation_state": {"readonly": True}, + "rpki_validation_state": {"readonly": True}, + "trust_anchor": {"readonly": True}, + "received_timestamp": {"readonly": True}, + } + + _attribute_map = { + "prefix": {"key": "prefix", "type": "str"}, + "next_hop": {"key": "nextHop", "type": "str"}, + "as_path": {"key": "asPath", "type": "str"}, + "origin_as_validation_state": {"key": "originAsValidationState", "type": "str"}, + "rpki_validation_state": {"key": "rpkiValidationState", "type": "str"}, + "trust_anchor": {"key": "trustAnchor", "type": "str"}, + "received_timestamp": {"key": "receivedTimestamp", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.prefix = None + self.next_hop = None + self.as_path = None + self.origin_as_validation_state = None + self.rpki_validation_state = None + self.trust_anchor = None + self.received_timestamp = None + + +class PeeringReceivedRouteListResult(_serialization.Model): + """The paginated list of received routes for the peering. + + :ivar value: The list of received routes for the peering. + :vartype value: list[~azure.mgmt.peering.models.PeeringReceivedRoute] + :ivar next_link: The link to fetch the next page of received routes for the peering. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PeeringReceivedRoute]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.PeeringReceivedRoute"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: The list of received routes for the peering. + :paramtype value: list[~azure.mgmt.peering.models.PeeringReceivedRoute] + :keyword next_link: The link to fetch the next page of received routes for the peering. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PeeringRegisteredAsn(Resource): + """The customer's ASN that is registered by the peering service provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the resource. + :vartype name: str + :ivar id: The ID of the resource. + :vartype id: str + :ivar type: The type of the resource. + :vartype type: str + :ivar asn: The customer's ASN from which traffic originates. + :vartype asn: int + :ivar peering_service_prefix_key: The peering service prefix key that is to be shared with the + customer. + :vartype peering_service_prefix_key: str + :ivar provisioning_state: The provisioning state of the resource. Known values are: + "Succeeded", "Updating", "Deleting", and "Failed". + :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState + """ + + _validation = { + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "peering_service_prefix_key": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "asn": {"key": "properties.asn", "type": "int"}, + "peering_service_prefix_key": {"key": "properties.peeringServicePrefixKey", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + } + + def __init__(self, *, asn: Optional[int] = None, **kwargs): + """ + :keyword asn: The customer's ASN from which traffic originates. + :paramtype asn: int + """ + super().__init__(**kwargs) + self.asn = asn + self.peering_service_prefix_key = None + self.provisioning_state = None + + +class PeeringRegisteredAsnListResult(_serialization.Model): + """The paginated list of peering registered ASNs. + + :ivar value: The list of peering registered ASNs. + :vartype value: list[~azure.mgmt.peering.models.PeeringRegisteredAsn] + :ivar next_link: The link to fetch the next page of peering registered ASNs. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PeeringRegisteredAsn]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.PeeringRegisteredAsn"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: The list of peering registered ASNs. + :paramtype value: list[~azure.mgmt.peering.models.PeeringRegisteredAsn] + :keyword next_link: The link to fetch the next page of peering registered ASNs. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PeeringRegisteredPrefix(Resource): + """The customer's prefix that is registered by the peering service provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the resource. + :vartype name: str + :ivar id: The ID of the resource. + :vartype id: str + :ivar type: The type of the resource. + :vartype type: str + :ivar prefix: The customer's prefix from which traffic originates. + :vartype prefix: str + :ivar prefix_validation_state: The prefix validation state. Known values are: "None", + "Invalid", "Verified", "Failed", "Pending", "Warning", and "Unknown". + :vartype prefix_validation_state: str or ~azure.mgmt.peering.models.PrefixValidationState + :ivar peering_service_prefix_key: The peering service prefix key that is to be shared with the + customer. + :vartype peering_service_prefix_key: str + :ivar error_message: The error message associated with the validation state, if any. + :vartype error_message: str + :ivar provisioning_state: The provisioning state of the resource. Known values are: + "Succeeded", "Updating", "Deleting", and "Failed". + :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState + """ + + _validation = { + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "prefix_validation_state": {"readonly": True}, + "peering_service_prefix_key": {"readonly": True}, + "error_message": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "prefix": {"key": "properties.prefix", "type": "str"}, + "prefix_validation_state": {"key": "properties.prefixValidationState", "type": "str"}, + "peering_service_prefix_key": {"key": "properties.peeringServicePrefixKey", "type": "str"}, + "error_message": {"key": "properties.errorMessage", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + } + + def __init__(self, *, prefix: Optional[str] = None, **kwargs): + """ + :keyword prefix: The customer's prefix from which traffic originates. + :paramtype prefix: str + """ + super().__init__(**kwargs) + self.prefix = prefix + self.prefix_validation_state = None + self.peering_service_prefix_key = None + self.error_message = None + self.provisioning_state = None + + +class PeeringRegisteredPrefixListResult(_serialization.Model): + """The paginated list of peering registered prefixes. + + :ivar value: The list of peering registered prefixes. + :vartype value: list[~azure.mgmt.peering.models.PeeringRegisteredPrefix] + :ivar next_link: The link to fetch the next page of peering registered prefixes. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PeeringRegisteredPrefix]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.PeeringRegisteredPrefix"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of peering registered prefixes. + :paramtype value: list[~azure.mgmt.peering.models.PeeringRegisteredPrefix] + :keyword next_link: The link to fetch the next page of peering registered prefixes. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PeeringService(Resource): # pylint: disable=too-many-instance-attributes """Peering Service. Variables are only populated by the server, and will be ignored when sending a request. @@ -943,83 +1744,194 @@ class PeeringService(Resource): :vartype id: str :ivar type: The type of the resource. :vartype type: str - :param location: Required. The location of the resource. - :type location: str - :param tags: A set of tags. The resource tags. - :type tags: dict[str, str] - :param peering_service_location: The PeeringServiceLocation of the Customer. - :type peering_service_location: str - :param peering_service_provider: The MAPS Provider Name. - :type peering_service_provider: str - :ivar provisioning_state: The provisioning state of the resource. Possible values include: - "Succeeded", "Updating", "Deleting", "Failed". + :ivar sku: The SKU that defines the type of the peering service. + :vartype sku: ~azure.mgmt.peering.models.PeeringServiceSku + :ivar location: The location of the resource. Required. + :vartype location: str + :ivar tags: The resource tags. + :vartype tags: dict[str, str] + :ivar peering_service_location: The location (state/province) of the customer. + :vartype peering_service_location: str + :ivar peering_service_provider: The name of the service provider. + :vartype peering_service_provider: str + :ivar provisioning_state: The provisioning state of the resource. Known values are: + "Succeeded", "Updating", "Deleting", and "Failed". :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState + :ivar provider_primary_peering_location: The primary peering (Microsoft/service provider) + location to be used for customer traffic. + :vartype provider_primary_peering_location: str + :ivar provider_backup_peering_location: The backup peering (Microsoft/service provider) + location to be used for customer traffic. + :vartype provider_backup_peering_location: str + :ivar log_analytics_workspace_properties: The Log Analytics Workspace Properties. + :vartype log_analytics_workspace_properties: + ~azure.mgmt.peering.models.LogAnalyticsWorkspaceProperties """ _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'provisioning_state': {'readonly': True}, + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'peering_service_location': {'key': 'properties.peeringServiceLocation', 'type': 'str'}, - 'peering_service_provider': {'key': 'properties.peeringServiceProvider', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "sku": {"key": "sku", "type": "PeeringServiceSku"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "peering_service_location": {"key": "properties.peeringServiceLocation", "type": "str"}, + "peering_service_provider": {"key": "properties.peeringServiceProvider", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "provider_primary_peering_location": {"key": "properties.providerPrimaryPeeringLocation", "type": "str"}, + "provider_backup_peering_location": {"key": "properties.providerBackupPeeringLocation", "type": "str"}, + "log_analytics_workspace_properties": { + "key": "properties.logAnalyticsWorkspaceProperties", + "type": "LogAnalyticsWorkspaceProperties", + }, } def __init__( self, *, location: str, + sku: Optional["_models.PeeringServiceSku"] = None, tags: Optional[Dict[str, str]] = None, peering_service_location: Optional[str] = None, peering_service_provider: Optional[str] = None, + provider_primary_peering_location: Optional[str] = None, + provider_backup_peering_location: Optional[str] = None, + log_analytics_workspace_properties: Optional["_models.LogAnalyticsWorkspaceProperties"] = None, **kwargs ): - super(PeeringService, self).__init__(**kwargs) + """ + :keyword sku: The SKU that defines the type of the peering service. + :paramtype sku: ~azure.mgmt.peering.models.PeeringServiceSku + :keyword location: The location of the resource. Required. + :paramtype location: str + :keyword tags: The resource tags. + :paramtype tags: dict[str, str] + :keyword peering_service_location: The location (state/province) of the customer. + :paramtype peering_service_location: str + :keyword peering_service_provider: The name of the service provider. + :paramtype peering_service_provider: str + :keyword provider_primary_peering_location: The primary peering (Microsoft/service provider) + location to be used for customer traffic. + :paramtype provider_primary_peering_location: str + :keyword provider_backup_peering_location: The backup peering (Microsoft/service provider) + location to be used for customer traffic. + :paramtype provider_backup_peering_location: str + :keyword log_analytics_workspace_properties: The Log Analytics Workspace Properties. + :paramtype log_analytics_workspace_properties: + ~azure.mgmt.peering.models.LogAnalyticsWorkspaceProperties + """ + super().__init__(**kwargs) + self.sku = sku self.location = location self.tags = tags self.peering_service_location = peering_service_location self.peering_service_provider = peering_service_provider self.provisioning_state = None + self.provider_primary_peering_location = provider_primary_peering_location + self.provider_backup_peering_location = provider_backup_peering_location + self.log_analytics_workspace_properties = log_analytics_workspace_properties -class PeeringServiceListResult(msrest.serialization.Model): - """The paginated list of peering services. +class PeeringServiceCountry(Resource): + """The peering service country. + + Variables are only populated by the server, and will be ignored when sending a request. - :param value: The list of peering services. - :type value: list[~azure.mgmt.peering.models.PeeringService] - :param next_link: The link to fetch the next page of peering services. - :type next_link: str + :ivar name: The name of the resource. + :vartype name: str + :ivar id: The ID of the resource. + :vartype id: str + :ivar type: The type of the resource. + :vartype type: str """ + _validation = { + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + } + _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringService]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + + +class PeeringServiceCountryListResult(_serialization.Model): + """The paginated list of peering service countries. + + :ivar value: The list of peering service countries. + :vartype value: list[~azure.mgmt.peering.models.PeeringServiceCountry] + :ivar next_link: The link to fetch the next page of peering service countries. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PeeringServiceCountry]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["PeeringService"]] = None, + value: Optional[List["_models.PeeringServiceCountry"]] = None, next_link: Optional[str] = None, **kwargs ): - super(PeeringServiceListResult, self).__init__(**kwargs) + """ + :keyword value: The list of peering service countries. + :paramtype value: list[~azure.mgmt.peering.models.PeeringServiceCountry] + :keyword next_link: The link to fetch the next page of peering service countries. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PeeringServiceListResult(_serialization.Model): + """The paginated list of peering services. + + :ivar value: The list of peering services. + :vartype value: list[~azure.mgmt.peering.models.PeeringService] + :ivar next_link: The link to fetch the next page of peering services. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[PeeringService]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.PeeringService"]] = None, next_link: Optional[str] = None, **kwargs + ): + """ + :keyword value: The list of peering services. + :paramtype value: list[~azure.mgmt.peering.models.PeeringService] + :keyword next_link: The link to fetch the next page of peering services. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link class PeeringServiceLocation(Resource): - """PeeringService location. + """The peering service location. Variables are only populated by the server, and will be ignored when sending a request. @@ -1029,27 +1941,27 @@ class PeeringServiceLocation(Resource): :vartype id: str :ivar type: The type of the resource. :vartype type: str - :param country: Country of the customer. - :type country: str - :param state: State of the customer. - :type state: str - :param azure_region: Azure region for the location. - :type azure_region: str + :ivar country: Country of the customer. + :vartype country: str + :ivar state: State of the customer. + :vartype state: str + :ivar azure_region: Azure region for the location. + :vartype azure_region: str """ _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'country': {'key': 'properties.country', 'type': 'str'}, - 'state': {'key': 'properties.state', 'type': 'str'}, - 'azure_region': {'key': 'properties.azureRegion', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "country": {"key": "properties.country", "type": "str"}, + "state": {"key": "properties.state", "type": "str"}, + "azure_region": {"key": "properties.azureRegion", "type": "str"}, } def __init__( @@ -1060,34 +1972,48 @@ def __init__( azure_region: Optional[str] = None, **kwargs ): - super(PeeringServiceLocation, self).__init__(**kwargs) + """ + :keyword country: Country of the customer. + :paramtype country: str + :keyword state: State of the customer. + :paramtype state: str + :keyword azure_region: Azure region for the location. + :paramtype azure_region: str + """ + super().__init__(**kwargs) self.country = country self.state = state self.azure_region = azure_region -class PeeringServiceLocationListResult(msrest.serialization.Model): +class PeeringServiceLocationListResult(_serialization.Model): """The paginated list of peering service locations. - :param value: The list of peering service locations. - :type value: list[~azure.mgmt.peering.models.PeeringServiceLocation] - :param next_link: The link to fetch the next page of peering service locations. - :type next_link: str + :ivar value: The list of peering service locations. + :vartype value: list[~azure.mgmt.peering.models.PeeringServiceLocation] + :ivar next_link: The link to fetch the next page of peering service locations. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringServiceLocation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PeeringServiceLocation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["PeeringServiceLocation"]] = None, + value: Optional[List["_models.PeeringServiceLocation"]] = None, next_link: Optional[str] = None, **kwargs ): - super(PeeringServiceLocationListResult, self).__init__(**kwargs) + """ + :keyword value: The list of peering service locations. + :paramtype value: list[~azure.mgmt.peering.models.PeeringServiceLocation] + :keyword next_link: The link to fetch the next page of peering service locations. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -1103,73 +2029,133 @@ class PeeringServicePrefix(Resource): :vartype id: str :ivar type: The type of the resource. :vartype type: str - :param prefix: Valid route prefix. - :type prefix: str - :param prefix_validation_state: The prefix validation state. Possible values include: "None", - "Invalid", "Verified", "Failed", "Pending", "Unknown". - :type prefix_validation_state: str or ~azure.mgmt.peering.models.PrefixValidationState - :param learned_type: The prefix learned type. Possible values include: "None", "ViaPartner", - "ViaSession". - :type learned_type: str or ~azure.mgmt.peering.models.LearnedType - :ivar provisioning_state: The provisioning state of the resource. Possible values include: - "Succeeded", "Updating", "Deleting", "Failed". + :ivar prefix: The prefix from which your traffic originates. + :vartype prefix: str + :ivar prefix_validation_state: The prefix validation state. Known values are: "None", + "Invalid", "Verified", "Failed", "Pending", "Warning", and "Unknown". + :vartype prefix_validation_state: str or ~azure.mgmt.peering.models.PrefixValidationState + :ivar learned_type: The prefix learned type. Known values are: "None", "ViaServiceProvider", + and "ViaSession". + :vartype learned_type: str or ~azure.mgmt.peering.models.LearnedType + :ivar error_message: The error message for validation state. + :vartype error_message: str + :ivar events: The list of events for peering service prefix. + :vartype events: list[~azure.mgmt.peering.models.PeeringServicePrefixEvent] + :ivar peering_service_prefix_key: The peering service prefix key. + :vartype peering_service_prefix_key: str + :ivar provisioning_state: The provisioning state of the resource. Known values are: + "Succeeded", "Updating", "Deleting", and "Failed". :vartype provisioning_state: str or ~azure.mgmt.peering.models.ProvisioningState """ _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'provisioning_state': {'readonly': True}, + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "prefix_validation_state": {"readonly": True}, + "learned_type": {"readonly": True}, + "error_message": {"readonly": True}, + "events": {"readonly": True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'prefix': {'key': 'properties.prefix', 'type': 'str'}, - 'prefix_validation_state': {'key': 'properties.prefixValidationState', 'type': 'str'}, - 'learned_type': {'key': 'properties.learnedType', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "prefix": {"key": "properties.prefix", "type": "str"}, + "prefix_validation_state": {"key": "properties.prefixValidationState", "type": "str"}, + "learned_type": {"key": "properties.learnedType", "type": "str"}, + "error_message": {"key": "properties.errorMessage", "type": "str"}, + "events": {"key": "properties.events", "type": "[PeeringServicePrefixEvent]"}, + "peering_service_prefix_key": {"key": "properties.peeringServicePrefixKey", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } - def __init__( - self, - *, - prefix: Optional[str] = None, - prefix_validation_state: Optional[Union[str, "PrefixValidationState"]] = None, - learned_type: Optional[Union[str, "LearnedType"]] = None, - **kwargs - ): - super(PeeringServicePrefix, self).__init__(**kwargs) + def __init__(self, *, prefix: Optional[str] = None, peering_service_prefix_key: Optional[str] = None, **kwargs): + """ + :keyword prefix: The prefix from which your traffic originates. + :paramtype prefix: str + :keyword peering_service_prefix_key: The peering service prefix key. + :paramtype peering_service_prefix_key: str + """ + super().__init__(**kwargs) self.prefix = prefix - self.prefix_validation_state = prefix_validation_state - self.learned_type = learned_type + self.prefix_validation_state = None + self.learned_type = None + self.error_message = None + self.events = None + self.peering_service_prefix_key = peering_service_prefix_key self.provisioning_state = None -class PeeringServicePrefixListResult(msrest.serialization.Model): - """The paginated list of [T]. +class PeeringServicePrefixEvent(_serialization.Model): + """The details of the event associated with a prefix. - :param value: The list of [T]. - :type value: list[~azure.mgmt.peering.models.PeeringServicePrefix] - :param next_link: The link to fetch the next page of [T]. - :type next_link: str + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar event_timestamp: The timestamp of the event associated with a prefix. + :vartype event_timestamp: ~datetime.datetime + :ivar event_type: The type of the event associated with a prefix. + :vartype event_type: str + :ivar event_summary: The summary of the event associated with a prefix. + :vartype event_summary: str + :ivar event_level: The level of the event associated with a prefix. + :vartype event_level: str + :ivar event_description: The description of the event associated with a prefix. + :vartype event_description: str + """ + + _validation = { + "event_timestamp": {"readonly": True}, + "event_type": {"readonly": True}, + "event_summary": {"readonly": True}, + "event_level": {"readonly": True}, + "event_description": {"readonly": True}, + } + + _attribute_map = { + "event_timestamp": {"key": "eventTimestamp", "type": "iso-8601"}, + "event_type": {"key": "eventType", "type": "str"}, + "event_summary": {"key": "eventSummary", "type": "str"}, + "event_level": {"key": "eventLevel", "type": "str"}, + "event_description": {"key": "eventDescription", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.event_timestamp = None + self.event_type = None + self.event_summary = None + self.event_level = None + self.event_description = None + + +class PeeringServicePrefixListResult(_serialization.Model): + """The paginated list of peering service prefixes. + + :ivar value: The list of peering service prefixes. + :vartype value: list[~azure.mgmt.peering.models.PeeringServicePrefix] + :ivar next_link: The link to fetch the next page of peering service prefixes. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringServicePrefix]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PeeringServicePrefix]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["PeeringServicePrefix"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.PeeringServicePrefix"]] = None, next_link: Optional[str] = None, **kwargs ): - super(PeeringServicePrefixListResult, self).__init__(**kwargs) + """ + :keyword value: The list of peering service prefixes. + :paramtype value: list[~azure.mgmt.peering.models.PeeringServicePrefix] + :keyword next_link: The link to fetch the next page of peering service prefixes. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -1185,135 +2171,253 @@ class PeeringServiceProvider(Resource): :vartype id: str :ivar type: The type of the resource. :vartype type: str - :param service_provider_name: The name of the service provider. - :type service_provider_name: str + :ivar service_provider_name: The name of the service provider. + :vartype service_provider_name: str + :ivar peering_locations: The list of locations at which the service provider peers with + Microsoft. + :vartype peering_locations: list[str] """ _validation = { - 'name': {'readonly': True}, - 'id': {'readonly': True}, - 'type': {'readonly': True}, + "name": {"readonly": True}, + "id": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'service_provider_name': {'key': 'properties.serviceProviderName', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "service_provider_name": {"key": "properties.serviceProviderName", "type": "str"}, + "peering_locations": {"key": "properties.peeringLocations", "type": "[str]"}, } def __init__( - self, - *, - service_provider_name: Optional[str] = None, - **kwargs + self, *, service_provider_name: Optional[str] = None, peering_locations: Optional[List[str]] = None, **kwargs ): - super(PeeringServiceProvider, self).__init__(**kwargs) + """ + :keyword service_provider_name: The name of the service provider. + :paramtype service_provider_name: str + :keyword peering_locations: The list of locations at which the service provider peers with + Microsoft. + :paramtype peering_locations: list[str] + """ + super().__init__(**kwargs) self.service_provider_name = service_provider_name + self.peering_locations = peering_locations -class PeeringServiceProviderListResult(msrest.serialization.Model): +class PeeringServiceProviderListResult(_serialization.Model): """The paginated list of peering service providers. - :param value: The list of peering service providers. - :type value: list[~azure.mgmt.peering.models.PeeringServiceProvider] - :param next_link: The link to fetch the next page of peering service providers. - :type next_link: str + :ivar value: The list of peering service providers. + :vartype value: list[~azure.mgmt.peering.models.PeeringServiceProvider] + :ivar next_link: The link to fetch the next page of peering service providers. + :vartype next_link: str """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PeeringServiceProvider]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PeeringServiceProvider]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["PeeringServiceProvider"]] = None, + value: Optional[List["_models.PeeringServiceProvider"]] = None, next_link: Optional[str] = None, **kwargs ): - super(PeeringServiceProviderListResult, self).__init__(**kwargs) + """ + :keyword value: The list of peering service providers. + :paramtype value: list[~azure.mgmt.peering.models.PeeringServiceProvider] + :keyword next_link: The link to fetch the next page of peering service providers. + :paramtype next_link: str + """ + super().__init__(**kwargs) self.value = value self.next_link = next_link -class PeeringSku(msrest.serialization.Model): +class PeeringServiceSku(_serialization.Model): + """The SKU that defines the type of the peering service. + + :ivar name: The name of the peering service SKU. + :vartype name: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, **kwargs): + """ + :keyword name: The name of the peering service SKU. + :paramtype name: str + """ + super().__init__(**kwargs) + self.name = name + + +class PeeringSku(_serialization.Model): """The SKU that defines the tier and kind of the peering. - :param name: The name of the peering SKU. Possible values include: "Basic_Exchange_Free", - "Basic_Direct_Free", "Premium_Direct_Free", "Premium_Exchange_Metered", - "Premium_Direct_Metered", "Premium_Direct_Unlimited". - :type name: str or ~azure.mgmt.peering.models.Name - :param tier: The tier of the peering SKU. Possible values include: "Basic", "Premium". - :type tier: str or ~azure.mgmt.peering.models.Tier - :param family: The family of the peering SKU. Possible values include: "Direct", "Exchange". - :type family: str or ~azure.mgmt.peering.models.Family - :param size: The size of the peering SKU. Possible values include: "Free", "Metered", - "Unlimited". - :type size: str or ~azure.mgmt.peering.models.Size + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the peering SKU. + :vartype name: str + :ivar tier: The tier of the peering SKU. Known values are: "Basic" and "Premium". + :vartype tier: str or ~azure.mgmt.peering.models.Tier + :ivar family: The family of the peering SKU. Known values are: "Direct" and "Exchange". + :vartype family: str or ~azure.mgmt.peering.models.Family + :ivar size: The size of the peering SKU. Known values are: "Free", "Metered", and "Unlimited". + :vartype size: str or ~azure.mgmt.peering.models.Size """ + _validation = { + "tier": {"readonly": True}, + "family": {"readonly": True}, + "size": {"readonly": True}, + } + _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'tier': {'key': 'tier', 'type': 'str'}, - 'family': {'key': 'family', 'type': 'str'}, - 'size': {'key': 'size', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + "family": {"key": "family", "type": "str"}, + "size": {"key": "size", "type": "str"}, } - def __init__( - self, - *, - name: Optional[Union[str, "Name"]] = None, - tier: Optional[Union[str, "Tier"]] = None, - family: Optional[Union[str, "Family"]] = None, - size: Optional[Union[str, "Size"]] = None, - **kwargs - ): - super(PeeringSku, self).__init__(**kwargs) + def __init__(self, *, name: Optional[str] = None, **kwargs): + """ + :keyword name: The name of the peering SKU. + :paramtype name: str + """ + super().__init__(**kwargs) self.name = name - self.tier = tier - self.family = family - self.size = size + self.tier = None + self.family = None + self.size = None -class ResourceTags(msrest.serialization.Model): +class ResourceTags(_serialization.Model): """The resource tags. - :param tags: A set of tags. Gets or sets the tags, a dictionary of descriptors arm object. - :type tags: dict[str, str] + :ivar tags: Gets or sets the tags, a dictionary of descriptors arm object. + :vartype tags: dict[str, str] """ _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, + "tags": {"key": "tags", "type": "{str}"}, } - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): - super(ResourceTags, self).__init__(**kwargs) + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs): + """ + :keyword tags: Gets or sets the tags, a dictionary of descriptors arm object. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) self.tags = tags -class SubResource(msrest.serialization.Model): - """The sub resource. +class RpUnbilledPrefix(_serialization.Model): + """The Routing Preference unbilled prefix. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar prefix: The prefix. + :vartype prefix: str + :ivar azure_region: The Azure region. + :vartype azure_region: str + :ivar peer_asn: The peer ASN. + :vartype peer_asn: int + """ + + _validation = { + "prefix": {"readonly": True}, + "azure_region": {"readonly": True}, + "peer_asn": {"readonly": True}, + } + + _attribute_map = { + "prefix": {"key": "prefix", "type": "str"}, + "azure_region": {"key": "azureRegion", "type": "str"}, + "peer_asn": {"key": "peerAsn", "type": "int"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.prefix = None + self.azure_region = None + self.peer_asn = None + + +class RpUnbilledPrefixListResult(_serialization.Model): + """The paginated list of RP unbilled prefixes. - :param id: The identifier of the referenced resource. - :type id: str + :ivar value: The list of RP unbilled prefixes. + :vartype value: list[~azure.mgmt.peering.models.RpUnbilledPrefix] + :ivar next_link: The link to fetch the next page of RP unbilled prefixes. + :vartype next_link: str """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "value": {"key": "value", "type": "[RpUnbilledPrefix]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - id: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.RpUnbilledPrefix"]] = None, next_link: Optional[str] = None, **kwargs ): - super(SubResource, self).__init__(**kwargs) + """ + :keyword value: The list of RP unbilled prefixes. + :paramtype value: list[~azure.mgmt.peering.models.RpUnbilledPrefix] + :keyword next_link: The link to fetch the next page of RP unbilled prefixes. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ServiceSpecification(_serialization.Model): + """Service specification payload. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar metric_specifications: Specifications of the Metrics for Azure Monitoring. + :vartype metric_specifications: list[~azure.mgmt.peering.models.MetricSpecification] + """ + + _validation = { + "metric_specifications": {"readonly": True}, + } + + _attribute_map = { + "metric_specifications": {"key": "metricSpecifications", "type": "[MetricSpecification]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.metric_specifications = None + + +class SubResource(_serialization.Model): + """The sub resource. + + :ivar id: The identifier of the referenced resource. + :vartype id: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin + """ + :keyword id: The identifier of the referenced resource. + :paramtype id: str + """ + super().__init__(**kwargs) self.id = id diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_patch.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_peering_management_client_enums.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_peering_management_client_enums.py index b44f84211b20..8ae0a7559e10 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_peering_management_client_enums.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/models/_peering_management_client_enums.py @@ -6,29 +6,20 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class ConnectionState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The state of the connection. - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class Command(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Invoked command.""" + + TRACEROUTE = "Traceroute" + PING = "Ping" + BGP_ROUTE = "BgpRoute" + + +class ConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state of the connection.""" NONE = "None" PENDING_APPROVAL = "PendingApproval" @@ -38,101 +29,135 @@ class ConnectionState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): PROVISIONING_COMPLETED = "ProvisioningCompleted" VALIDATING = "Validating" ACTIVE = "Active" + TYPE_CHANGE_REQUESTED = "TypeChangeRequested" + TYPE_CHANGE_IN_PROGRESS = "TypeChangeInProgress" + -class DirectPeeringType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of direct peering. - """ +class DirectPeeringType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of direct peering.""" EDGE = "Edge" TRANSIT = "Transit" CDN = "Cdn" INTERNAL = "Internal" + IX = "Ix" + IX_RS = "IxRs" + VOICE = "Voice" + EDGE_ZONE_FOR_OPERATORS = "EdgeZoneForOperators" -class Enum0(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class Enum0(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum0.""" AVAILABLE = "Available" - UN_AVAILABLE = "UnAvailable" + UNAVAILABLE = "Unavailable" + -class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class Family(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The family of the peering SKU.""" DIRECT = "Direct" EXCHANGE = "Exchange" -class Enum14(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class Kind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of the peering.""" DIRECT = "Direct" EXCHANGE = "Exchange" -class Enum15(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - EDGE = "Edge" - TRANSIT = "Transit" - CDN = "Cdn" - INTERNAL = "Internal" +class LearnedType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The prefix learned type.""" -class Family(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The family of the peering SKU. - """ + NONE = "None" + VIA_SERVICE_PROVIDER = "ViaServiceProvider" + VIA_SESSION = "ViaSession" - DIRECT = "Direct" - EXCHANGE = "Exchange" -class Kind(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The kind of the peering. - """ +class LegacyPeeringsKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """LegacyPeeringsKind.""" DIRECT = "Direct" EXCHANGE = "Exchange" -class LearnedType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The prefix learned type - """ - NONE = "None" - VIA_PARTNER = "ViaPartner" - VIA_SESSION = "ViaSession" +class LookingGlassCommand(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """LookingGlassCommand.""" + + TRACEROUTE = "Traceroute" + PING = "Ping" + BGP_ROUTE = "BgpRoute" + + +class LookingGlassSourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """LookingGlassSourceType.""" -class Name(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The name of the peering SKU. - """ + EDGE_SITE = "EdgeSite" + AZURE_REGION = "AzureRegion" - BASIC_EXCHANGE_FREE = "Basic_Exchange_Free" - BASIC_DIRECT_FREE = "Basic_Direct_Free" - PREMIUM_DIRECT_FREE = "Premium_Direct_Free" - PREMIUM_EXCHANGE_METERED = "Premium_Exchange_Metered" - PREMIUM_DIRECT_METERED = "Premium_Direct_Metered" - PREMIUM_DIRECT_UNLIMITED = "Premium_Direct_Unlimited" -class PrefixValidationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The prefix validation state - """ +class PeeringLocationsDirectPeeringType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PeeringLocationsDirectPeeringType.""" + + EDGE = "Edge" + TRANSIT = "Transit" + CDN = "Cdn" + INTERNAL = "Internal" + IX = "Ix" + IX_RS = "IxRs" + VOICE = "Voice" + EDGE_ZONE_FOR_OPERATORS = "EdgeZoneForOperators" + + +class PeeringLocationsKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PeeringLocationsKind.""" + + DIRECT = "Direct" + EXCHANGE = "Exchange" + + +class PrefixValidationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The prefix validation state.""" NONE = "None" INVALID = "Invalid" VERIFIED = "Verified" FAILED = "Failed" PENDING = "Pending" + WARNING = "Warning" UNKNOWN = "Unknown" -class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state of the resource. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state of the resource.""" SUCCEEDED = "Succeeded" UPDATING = "Updating" DELETING = "Deleting" FAILED = "Failed" -class SessionAddressProvider(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The field indicating if Microsoft provides session ip addresses. - """ + +class Role(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The role of the contact.""" + + NOC = "Noc" + POLICY = "Policy" + TECHNICAL = "Technical" + SERVICE = "Service" + ESCALATION = "Escalation" + OTHER = "Other" + + +class SessionAddressProvider(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The field indicating if Microsoft provides session ip addresses.""" MICROSOFT = "Microsoft" PEER = "Peer" -class SessionStateV4(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The state of the IPv4 session. - """ + +class SessionStateV4(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state of the IPv4 session.""" NONE = "None" IDLE = "Idle" @@ -146,9 +171,9 @@ class SessionStateV4(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): PENDING_UPDATE = "PendingUpdate" PENDING_REMOVE = "PendingRemove" -class SessionStateV6(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The state of the IPv6 session. - """ + +class SessionStateV6(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The state of the IPv6 session.""" NONE = "None" IDLE = "Idle" @@ -162,24 +187,24 @@ class SessionStateV6(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): PENDING_UPDATE = "PendingUpdate" PENDING_REMOVE = "PendingRemove" -class Size(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The size of the peering SKU. - """ + +class Size(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The size of the peering SKU.""" FREE = "Free" METERED = "Metered" UNLIMITED = "Unlimited" -class Tier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The tier of the peering SKU. - """ + +class Tier(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The tier of the peering SKU.""" BASIC = "Basic" PREMIUM = "Premium" -class ValidationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The validation state of the ASN associated with the peer. - """ + +class ValidationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The validation state of the ASN associated with the peer.""" NONE = "None" PENDING = "Pending" diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/__init__.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/__init__.py index 2c62d44850a9..3a7f6307d71e 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/__init__.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/__init__.py @@ -6,28 +6,48 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from ._cdn_peering_prefixes_operations import CdnPeeringPrefixesOperations from ._peering_management_client_operations import PeeringManagementClientOperationsMixin from ._legacy_peerings_operations import LegacyPeeringsOperations +from ._looking_glass_operations import LookingGlassOperations from ._operations import Operations from ._peer_asns_operations import PeerAsnsOperations from ._peering_locations_operations import PeeringLocationsOperations +from ._registered_asns_operations import RegisteredAsnsOperations +from ._registered_prefixes_operations import RegisteredPrefixesOperations from ._peerings_operations import PeeringsOperations +from ._received_routes_operations import ReceivedRoutesOperations +from ._connection_monitor_tests_operations import ConnectionMonitorTestsOperations +from ._peering_service_countries_operations import PeeringServiceCountriesOperations from ._peering_service_locations_operations import PeeringServiceLocationsOperations -from ._peering_service_prefixes_operations import PeeringServicePrefixesOperations from ._prefixes_operations import PrefixesOperations from ._peering_service_providers_operations import PeeringServiceProvidersOperations from ._peering_services_operations import PeeringServicesOperations +from ._rp_unbilled_prefixes_operations import RpUnbilledPrefixesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'PeeringManagementClientOperationsMixin', - 'LegacyPeeringsOperations', - 'Operations', - 'PeerAsnsOperations', - 'PeeringLocationsOperations', - 'PeeringsOperations', - 'PeeringServiceLocationsOperations', - 'PeeringServicePrefixesOperations', - 'PrefixesOperations', - 'PeeringServiceProvidersOperations', - 'PeeringServicesOperations', + "CdnPeeringPrefixesOperations", + "PeeringManagementClientOperationsMixin", + "LegacyPeeringsOperations", + "LookingGlassOperations", + "Operations", + "PeerAsnsOperations", + "PeeringLocationsOperations", + "RegisteredAsnsOperations", + "RegisteredPrefixesOperations", + "PeeringsOperations", + "ReceivedRoutesOperations", + "ConnectionMonitorTestsOperations", + "PeeringServiceCountriesOperations", + "PeeringServiceLocationsOperations", + "PrefixesOperations", + "PeeringServiceProvidersOperations", + "PeeringServicesOperations", + "RpUnbilledPrefixesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_cdn_peering_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_cdn_peering_prefixes_operations.py new file mode 100644 index 000000000000..c5ab3a4d6687 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_cdn_peering_prefixes_operations.py @@ -0,0 +1,171 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, *, peering_location: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/cdnPeeringPrefixes") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["peeringLocation"] = _SERIALIZER.query("peering_location", peering_location, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class CdnPeeringPrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`cdn_peering_prefixes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, peering_location: str, **kwargs: Any) -> Iterable["_models.CdnPeeringPrefix"]: + """Lists all of the advertised prefixes for the specified peering location. + + :param peering_location: The peering location. Required. + :type peering_location: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either CdnPeeringPrefix or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.CdnPeeringPrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CdnPeeringPrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + peering_location=peering_location, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("CdnPeeringPrefixListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/cdnPeeringPrefixes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_connection_monitor_tests_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_connection_monitor_tests_operations.py new file mode 100644 index 000000000000..a68ecbcfa0bd --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_connection_monitor_tests_operations.py @@ -0,0 +1,589 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request( + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "connectionMonitorTestName": _SERIALIZER.url( + "connection_monitor_test_name", connection_monitor_test_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "connectionMonitorTestName": _SERIALIZER.url( + "connection_monitor_test_name", connection_monitor_test_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "connectionMonitorTestName": _SERIALIZER.url( + "connection_monitor_test_name", connection_monitor_test_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_peering_service_request( + resource_group_name: str, peering_service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ConnectionMonitorTestsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`connection_monitor_tests` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, peering_service_name: str, connection_monitor_test_name: str, **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Gets an existing connection monitor test with the specified name under the given subscription, + resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConnectionMonitorTest] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + connection_monitor_test_name=connection_monitor_test_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ConnectionMonitorTest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}"} # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + connection_monitor_test: _models.ConnectionMonitorTest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Creates or updates a connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :param connection_monitor_test: The properties needed to create a connection monitor test. + Required. + :type connection_monitor_test: ~azure.mgmt.peering.models.ConnectionMonitorTest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + connection_monitor_test: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Creates or updates a connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :param connection_monitor_test: The properties needed to create a connection monitor test. + Required. + :type connection_monitor_test: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + connection_monitor_test_name: str, + connection_monitor_test: Union[_models.ConnectionMonitorTest, IO], + **kwargs: Any + ) -> _models.ConnectionMonitorTest: + """Creates or updates a connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :param connection_monitor_test: The properties needed to create a connection monitor test. Is + either a model type or a IO type. Required. + :type connection_monitor_test: ~azure.mgmt.peering.models.ConnectionMonitorTest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ConnectionMonitorTest or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.ConnectionMonitorTest + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConnectionMonitorTest] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(connection_monitor_test, (IO, bytes)): + _content = connection_monitor_test + else: + _json = self._serialize.body(connection_monitor_test, "ConnectionMonitorTest") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + connection_monitor_test_name=connection_monitor_test_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ConnectionMonitorTest", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ConnectionMonitorTest", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_service_name: str, connection_monitor_test_name: str, **kwargs: Any + ) -> None: + """Deletes an existing connection monitor test with the specified name under the given + subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param connection_monitor_test_name: The name of the connection monitor test. Required. + :type connection_monitor_test_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + connection_monitor_test_name=connection_monitor_test_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests/{connectionMonitorTestName}"} # type: ignore + + @distributed_trace + def list_by_peering_service( + self, resource_group_name: str, peering_service_name: str, **kwargs: Any + ) -> Iterable["_models.ConnectionMonitorTest"]: + """Lists all connection monitor tests under the given subscription, resource group and peering + service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ConnectionMonitorTest or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.ConnectionMonitorTest] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConnectionMonitorTestListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_service_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_peering_service.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ConnectionMonitorTestListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_peering_service.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/connectionMonitorTests"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_legacy_peerings_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_legacy_peerings_operations.py index 2f30feb21622..d970eac838d6 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_legacy_peerings_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_legacy_peerings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,100 +6,177 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + subscription_id: str, + *, + peering_location: str, + kind: Union[str, _models.LegacyPeeringsKind], + asn: Optional[int] = None, + direct_peering_type: Optional[Union[str, _models.DirectPeeringType]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/legacyPeerings") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["peeringLocation"] = _SERIALIZER.query("peering_location", peering_location, "str") + _params["kind"] = _SERIALIZER.query("kind", kind, "str") + if asn is not None: + _params["asn"] = _SERIALIZER.query("asn", asn, "int") + if direct_peering_type is not None: + _params["directPeeringType"] = _SERIALIZER.query("direct_peering_type", direct_peering_type, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class LegacyPeeringsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class LegacyPeeringsOperations(object): - """LegacyPeeringsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`legacy_peerings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( self, - peering_location, # type: str - kind, # type: Union[str, "_models.Enum1"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringListResult"] + peering_location: str, + kind: Union[str, _models.LegacyPeeringsKind], + asn: Optional[int] = None, + direct_peering_type: Optional[Union[str, _models.DirectPeeringType]] = None, + **kwargs: Any + ) -> Iterable["_models.Peering"]: """Lists all of the legacy peerings under the given subscription matching the specified kind and location. - :param peering_location: The location of the peering. + :param peering_location: The location of the peering. Required. :type peering_location: str - :param kind: The kind of the peering. - :type kind: str or ~azure.mgmt.peering.models.Enum1 + :param kind: The kind of the peering. Known values are: "Direct" and "Exchange". Required. + :type kind: str or ~azure.mgmt.peering.models.LegacyPeeringsKind + :param asn: The ASN number associated with a legacy peering. Default value is None. + :type asn: int + :param direct_peering_type: The direct peering type. Known values are: "Edge", "Transit", + "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". Default value is None. + :type direct_peering_type: str or ~azure.mgmt.peering.models.DirectPeeringType :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Peering or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.Peering] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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['peeringLocation'] = self._serialize.query("peering_location", peering_location, 'str') - query_parameters['kind'] = self._serialize.query("kind", kind, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + peering_location=peering_location, + kind=kind, + asn=asn, + direct_peering_type=direct_peering_type, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringListResult', pipeline_response) + deserialized = self._deserialize("PeeringListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -107,17 +185,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/legacyPeerings'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/legacyPeerings"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_looking_glass_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_looking_glass_operations.py new file mode 100644 index 000000000000..2af46f69d4b7 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_looking_glass_operations.py @@ -0,0 +1,171 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_invoke_request( + subscription_id: str, + *, + command: Union[str, _models.LookingGlassCommand], + source_type: Union[str, _models.LookingGlassSourceType], + source_location: str, + destination_ip: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/lookingGlass") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["command"] = _SERIALIZER.query("command", command, "str") + _params["sourceType"] = _SERIALIZER.query("source_type", source_type, "str") + _params["sourceLocation"] = _SERIALIZER.query("source_location", source_location, "str") + _params["destinationIP"] = _SERIALIZER.query("destination_ip", destination_ip, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class LookingGlassOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`looking_glass` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def invoke( + self, + command: Union[str, _models.LookingGlassCommand], + source_type: Union[str, _models.LookingGlassSourceType], + source_location: str, + destination_ip: str, + **kwargs: Any + ) -> _models.LookingGlassOutput: + """Run looking glass functionality. + + :param command: The command to be executed: ping, traceroute, bgpRoute. Known values are: + "Traceroute", "Ping", and "BgpRoute". Required. + :type command: str or ~azure.mgmt.peering.models.LookingGlassCommand + :param source_type: The type of the source: Edge site or Azure Region. Known values are: + "EdgeSite" and "AzureRegion". Required. + :type source_type: str or ~azure.mgmt.peering.models.LookingGlassSourceType + :param source_location: The location of the source. Required. + :type source_location: str + :param destination_ip: The IP address of the destination. Required. + :type destination_ip: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: LookingGlassOutput or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.LookingGlassOutput + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.LookingGlassOutput] + + request = build_invoke_request( + subscription_id=self._config.subscription_id, + command=command, + source_type=source_type, + source_location=source_location, + destination_ip=destination_ip, + api_version=api_version, + template_url=self.invoke.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("LookingGlassOutput", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + invoke.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/lookingGlass"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_operations.py index 8d739364523e..c2b4670c0fc5 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,136 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") -class Operations(object): - """Operations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Peering/operations") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available API operations for peering resources. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +144,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Peering/operations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Peering/operations"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_patch.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peer_asns_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peer_asns_operations.py index 65ab692f263f..efb780b22bd7 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peer_asns_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peer_asns_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,269 +6,460 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(peer_asn_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}" + ) + path_format_arguments = { + "peerAsnName": _SERIALIZER.url("peer_asn_name", peer_asn_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(peer_asn_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}" + ) + path_format_arguments = { + "peerAsnName": _SERIALIZER.url("peer_asn_name", peer_asn_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -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]] +def build_delete_request(peer_asn_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -class PeerAsnsOperations(object): - """PeerAsnsOperations operations. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}" + ) + path_format_arguments = { + "peerAsnName": _SERIALIZER.url("peer_asn_name", peer_asn_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PeerAsnsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`peer_asns` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - peer_asn_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.PeerAsn" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, peer_asn_name: str, **kwargs: Any) -> _models.PeerAsn: """Gets the peer ASN with the specified name under the given subscription. - :param peer_asn_name: The peer ASN name. + :param peer_asn_name: The peer ASN name. Required. :type peer_asn_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeerAsn, or the result of cls(response) + :return: PeerAsn or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeerAsn - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeerAsn"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'peerAsnName': self._serialize.url("peer_asn_name", peer_asn_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeerAsn] + + request = build_get_request( + peer_asn_name=peer_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PeerAsn', pipeline_response) + deserialized = self._deserialize("PeerAsn", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}"} # type: ignore + + @overload def create_or_update( - self, - peer_asn_name, # type: str - peer_asn, # type: "_models.PeerAsn" - **kwargs # type: Any - ): - # type: (...) -> "_models.PeerAsn" + self, peer_asn_name: str, peer_asn: _models.PeerAsn, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PeerAsn: """Creates a new peer ASN or updates an existing peer ASN with the specified name under the given subscription. - :param peer_asn_name: The peer ASN name. + :param peer_asn_name: The peer ASN name. Required. :type peer_asn_name: str - :param peer_asn: The peer ASN. + :param peer_asn: The peer ASN. Required. :type peer_asn: ~azure.mgmt.peering.models.PeerAsn + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeerAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeerAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, peer_asn_name: str, peer_asn: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PeerAsn: + """Creates a new peer ASN or updates an existing peer ASN with the specified name under the given + subscription. + + :param peer_asn_name: The peer ASN name. Required. + :type peer_asn_name: str + :param peer_asn: The peer ASN. Required. + :type peer_asn: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeerAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeerAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, peer_asn_name: str, peer_asn: Union[_models.PeerAsn, IO], **kwargs: Any + ) -> _models.PeerAsn: + """Creates a new peer ASN or updates an existing peer ASN with the specified name under the given + subscription. + + :param peer_asn_name: The peer ASN name. Required. + :type peer_asn_name: str + :param peer_asn: The peer ASN. Is either a model type or a IO type. Required. + :type peer_asn: ~azure.mgmt.peering.models.PeerAsn or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeerAsn, or the result of cls(response) + :return: PeerAsn or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeerAsn - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeerAsn"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'peerAsnName': self._serialize.url("peer_asn_name", peer_asn_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peer_asn, 'PeerAsn') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeerAsn] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peer_asn, (IO, bytes)): + _content = peer_asn + else: + _json = self._serialize.body(peer_asn, "PeerAsn") + + request = build_create_or_update_request( + peer_asn_name=peer_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PeerAsn', pipeline_response) + deserialized = self._deserialize("PeerAsn", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('PeerAsn', pipeline_response) + deserialized = self._deserialize("PeerAsn", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}'} # type: ignore - - def delete( - self, - peer_asn_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}"} # type: ignore + + @distributed_trace + def delete(self, peer_asn_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """Deletes an existing peer ASN with the specified name under the given subscription. - :param peer_asn_name: The peer ASN name. + :param peer_asn_name: The peer ASN name. Required. :type peer_asn_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'peerAsnName': self._serialize.url("peer_asn_name", peer_asn_name, 'str'), - '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') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + peer_asn_name=peer_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}'} # type: ignore + delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns/{peerAsnName}"} # type: ignore - def list_by_subscription( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeerAsnListResult"] + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.PeerAsn"]: """Lists all of the peer ASNs under the given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeerAsnListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeerAsnListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeerAsn or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeerAsn] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeerAsnListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeerAsnListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_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, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeerAsnListResult', pipeline_response) + deserialized = self._deserialize("PeerAsnListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -276,17 +468,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerAsns"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_locations_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_locations_operations.py index 695151180cf7..b90176dcc921 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_locations_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_locations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,100 +6,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 warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + subscription_id: str, + *, + kind: Union[str, _models.PeeringLocationsKind], + direct_peering_type: Optional[Union[str, _models.PeeringLocationsDirectPeeringType]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringLocations") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + # Construct parameters + _params["kind"] = _SERIALIZER.query("kind", kind, "str") + if direct_peering_type is not None: + _params["directPeeringType"] = _SERIALIZER.query("direct_peering_type", direct_peering_type, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class PeeringLocationsOperations(object): - """PeeringLocationsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class PeeringLocationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`peering_locations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( self, - kind, # type: Union[str, "_models.Enum14"] - direct_peering_type=None, # type: Optional[Union[str, "_models.Enum15"]] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringLocationListResult"] + kind: Union[str, _models.PeeringLocationsKind], + direct_peering_type: Optional[Union[str, _models.PeeringLocationsDirectPeeringType]] = None, + **kwargs: Any + ) -> Iterable["_models.PeeringLocation"]: """Lists all of the available peering locations for the specified kind of peering. - :param kind: The kind of the peering. - :type kind: str or ~azure.mgmt.peering.models.Enum14 - :param direct_peering_type: The type of direct peering. - :type direct_peering_type: str or ~azure.mgmt.peering.models.Enum15 + :param kind: The kind of the peering. Known values are: "Direct" and "Exchange". Required. + :type kind: str or ~azure.mgmt.peering.models.PeeringLocationsKind + :param direct_peering_type: The type of direct peering. Known values are: "Edge", "Transit", + "Cdn", "Internal", "Ix", "IxRs", "Voice", and "EdgeZoneForOperators". Default value is None. + :type direct_peering_type: str or ~azure.mgmt.peering.models.PeeringLocationsDirectPeeringType :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringLocationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringLocationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringLocation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringLocation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringLocationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringLocationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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['kind'] = self._serialize.query("kind", kind, 'str') - if direct_peering_type is not None: - query_parameters['directPeeringType'] = self._serialize.query("direct_peering_type", direct_peering_type, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + kind=kind, + direct_peering_type=direct_peering_type, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringLocationListResult', pipeline_response) + deserialized = self._deserialize("PeeringLocationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -107,17 +171,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringLocations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringLocations"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_management_client_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_management_client_operations.py index 2aef6f9bc969..b5a8202c5aeb 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_management_client_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_management_client_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,187 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class PeeringManagementClientOperationsMixin(object): +def build_check_service_provider_availability_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/checkServiceProviderAvailability" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class PeeringManagementClientOperationsMixin(PeeringManagementClientMixinABC): + @overload def check_service_provider_availability( self, - check_service_provider_availability_input, # type: "_models.CheckServiceProviderAvailabilityInput" - **kwargs # type: Any - ): - # type: (...) -> Union[str, "_models.Enum0"] + check_service_provider_availability_input: _models.CheckServiceProviderAvailabilityInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Union[str, _models.Enum0]: """Checks if the peering service provider is present within 1000 miles of customer's location. :param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput - indicating customer location and service provider. - :type check_service_provider_availability_input: ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput + indicating customer location and service provider. Required. + :type check_service_provider_availability_input: + ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Enum0, or the result of cls(response) + :return: Enum0 or the result of cls(response) :rtype: str or ~azure.mgmt.peering.models.Enum0 - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_service_provider_availability( + self, check_service_provider_availability_input: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> Union[str, _models.Enum0]: + """Checks if the peering service provider is present within 1000 miles of customer's location. + + :param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput + indicating customer location and service provider. Required. + :type check_service_provider_availability_input: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Enum0 or the result of cls(response) + :rtype: str or ~azure.mgmt.peering.models.Enum0 + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_service_provider_availability( + self, + check_service_provider_availability_input: Union[_models.CheckServiceProviderAvailabilityInput, IO], + **kwargs: Any + ) -> Union[str, _models.Enum0]: + """Checks if the peering service provider is present within 1000 miles of customer's location. + + :param check_service_provider_availability_input: The CheckServiceProviderAvailabilityInput + indicating customer location and service provider. Is either a model type or a IO type. + Required. + :type check_service_provider_availability_input: + ~azure.mgmt.peering.models.CheckServiceProviderAvailabilityInput or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Enum0 or the result of cls(response) + :rtype: str or ~azure.mgmt.peering.models.Enum0 + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Union[str, "_models.Enum0"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.check_service_provider_availability.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] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(check_service_provider_availability_input, 'CheckServiceProviderAvailabilityInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Union[str, _models.Enum0]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(check_service_provider_availability_input, (IO, bytes)): + _content = check_service_provider_availability_input + else: + _json = self._serialize.body( + check_service_provider_availability_input, "CheckServiceProviderAvailabilityInput" + ) + + request = build_check_service_provider_availability_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_service_provider_availability.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('str', pipeline_response) + deserialized = self._deserialize("str", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_service_provider_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/CheckServiceProviderAvailability'} # type: ignore + + check_service_provider_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/checkServiceProviderAvailability"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_countries_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_countries_operations.py new file mode 100644 index 000000000000..99ca672237f8 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_countries_operations.py @@ -0,0 +1,170 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceCountries" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PeeringServiceCountriesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`peering_service_countries` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.PeeringServiceCountry"]: + """Lists all of the available countries for peering service. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringServiceCountry or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServiceCountry] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceCountryListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringServiceCountryListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceCountries"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_locations_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_locations_operations.py index 0675861a8f49..7c3fd9ab488f 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_locations_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_locations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,151 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, *, country: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceLocations" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + if country is not None: + _params["country"] = _SERIALIZER.query("country", country, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class PeeringServiceLocationsOperations(object): - """PeeringServiceLocationsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class PeeringServiceLocationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`peering_service_locations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringServiceLocationListResult"] - """Lists all of the available peering service locations for the specified kind of peering. + @distributed_trace + def list(self, country: Optional[str] = None, **kwargs: Any) -> Iterable["_models.PeeringServiceLocation"]: + """Lists all of the available locations for peering service. + :param country: The country of interest, in which the locations are to be present. Default + value is None. + :type country: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceLocationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServiceLocationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringServiceLocation or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServiceLocation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceLocationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceLocationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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_request( + subscription_id=self._config.subscription_id, + country=country, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceLocationListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceLocationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -98,17 +159,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceLocations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceLocations"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_prefixes_operations.py deleted file mode 100644 index 32253e9072c0..000000000000 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_prefixes_operations.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class PeeringServicePrefixesOperations(object): - """PeeringServicePrefixesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - """ - - models = _models - - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - resource_group_name, # type: str - peering_service_name, # type: str - prefix_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.PeeringServicePrefix" - """Gets the peering service prefix. - - :param resource_group_name: The resource group name. - :type resource_group_name: str - :param peering_service_name: The peering service name. - :type peering_service_name: str - :param prefix_name: The prefix name. - :type prefix_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringServicePrefix, or the result of cls(response) - :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefix"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), - '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] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore - - def create_or_update( - self, - resource_group_name, # type: str - peering_service_name, # type: str - prefix_name, # type: str - peering_service_prefix, # type: "_models.PeeringServicePrefix" - **kwargs # type: Any - ): - # type: (...) -> "_models.PeeringServicePrefix" - """Creates or updates the peering prefix. - - :param resource_group_name: The resource group name. - :type resource_group_name: str - :param peering_service_name: The peering service name. - :type peering_service_name: str - :param prefix_name: The prefix name. - :type prefix_name: str - :param peering_service_prefix: The IP prefix for an peering. - :type peering_service_prefix: ~azure.mgmt.peering.models.PeeringServicePrefix - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringServicePrefix, or the result of cls(response) - :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefix"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), - '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] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peering_service_prefix, 'PeeringServicePrefix') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore - - def delete( - self, - resource_group_name, # type: str - peering_service_name, # type: str - prefix_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - """removes the peering prefix. - - :param resource_group_name: The resource group name. - :type resource_group_name: str - :param peering_service_name: The peering service name. - :type peering_service_name: str - :param prefix_name: The prefix name. - :type prefix_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), - '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] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_providers_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_providers_operations.py index b8a112a01d7c..4733ba0e1562 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_providers_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_service_providers_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,91 +6,145 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceProviders" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } -class PeeringServiceProvidersOperations(object): - """PeeringServiceProvidersOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PeeringServiceProvidersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`peering_service_providers` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringServiceProviderListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.PeeringServiceProvider"]: """Lists all of the available peering service locations for the specified kind of peering. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceProviderListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServiceProviderListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringServiceProvider or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServiceProvider] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceProviderListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceProviderListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - '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_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceProviderListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceProviderListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -98,17 +153,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceProviders'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServiceProviders"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_services_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_services_operations.py index e7b671195eec..3e6069062833 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_services_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peering_services_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,356 +6,734 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request( + resource_group_name: str, peering_service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, peering_service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, peering_service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, peering_service_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") -class PeeringServicesOperations(object): - """PeeringServicesOperations operations. + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServices") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + _url = _format_url_section(_url, **path_format_arguments) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_initialize_connection_monitor_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/initializeConnectionMonitor" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class PeeringServicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`peering_services` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get( - self, - resource_group_name, # type: str - peering_service_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.PeeringService" + @distributed_trace + def get(self, resource_group_name: str, peering_service_name: str, **kwargs: Any) -> _models.PeeringService: """Gets an existing peering service with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering. + :param peering_service_name: The name of the peering. Required. :type peering_service_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringService, or the result of cls(response) + :return: PeeringService or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringService - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringService"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - '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') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringService] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + + @overload def create_or_update( self, - resource_group_name, # type: str - peering_service_name, # type: str - peering_service, # type: "_models.PeeringService" - **kwargs # type: Any - ): - # type: (...) -> "_models.PeeringService" + resource_group_name: str, + peering_service_name: str, + peering_service: _models.PeeringService, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: """Creates a new peering service or updates an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering service. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str - :param peering_service: The properties needed to create or update a peering service. + :param peering_service: The properties needed to create or update a peering service. Required. :type peering_service: ~azure.mgmt.peering.models.PeeringService + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + peering_service: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: + """Creates a new peering service or updates an existing peering with the specified name under the + given subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param peering_service: The properties needed to create or update a peering service. Required. + :type peering_service: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + peering_service: Union[_models.PeeringService, IO], + **kwargs: Any + ) -> _models.PeeringService: + """Creates a new peering service or updates an existing peering with the specified name under the + given subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param peering_service: The properties needed to create or update a peering service. Is either + a model type or a IO type. Required. + :type peering_service: ~azure.mgmt.peering.models.PeeringService or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringService, or the result of cls(response) + :return: PeeringService or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringService - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringService"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peering_service, 'PeeringService') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringService] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peering_service, (IO, bytes)): + _content = peering_service + else: + _json = self._serialize.body(peering_service, "PeeringService") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore - def delete( - self, - resource_group_name, # type: str - peering_service_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_service_name: str, **kwargs: Any + ) -> None: """Deletes an existing peering service with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering service. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + @overload def update( self, - resource_group_name, # type: str - peering_service_name, # type: str - tags, # type: "_models.ResourceTags" - **kwargs # type: Any - ): - # type: (...) -> "_models.PeeringService" + resource_group_name: str, + peering_service_name: str, + tags: _models.ResourceTags, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: """Updates tags for a peering service with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The name of the peering service. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str - :param tags: The resource tags. + :param tags: The resource tags. Required. :type tags: ~azure.mgmt.peering.models.ResourceTags + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + peering_service_name: str, + tags: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringService: + """Updates tags for a peering service with the specified name under the given subscription and + resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param tags: The resource tags. Required. + :type tags: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PeeringService, or the result of cls(response) + :return: PeeringService or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringService - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, resource_group_name: str, peering_service_name: str, tags: Union[_models.ResourceTags, IO], **kwargs: Any + ) -> _models.PeeringService: + """Updates tags for a peering service with the specified name under the given subscription and + resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param tags: The resource tags. Is either a model type or a IO type. Required. + :type tags: ~azure.mgmt.peering.models.ResourceTags or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringService or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringService + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringService"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - '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] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(tags, 'ResourceTags') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringService] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(tags, (IO, bytes)): + _content = tags + else: + _json = self._serialize.body(tags, "ResourceTags") + + request = build_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PeeringService', pipeline_response) + deserialized = self._deserialize("PeeringService", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}'} # type: ignore - def list_by_resource_group( - self, - resource_group_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringServiceListResult"] + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}"} # type: ignore + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.PeeringService"]: """Lists all of the peering services under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringService or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringService] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - '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_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -363,66 +742,80 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices'} # type: ignore + return ItemPaged(get_next, extract_data) - def list_by_subscription( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringServiceListResult"] + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices"} # type: ignore + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.PeeringService"]: """Lists all of the peerings under the given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServiceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PeeringService or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringService] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_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, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServiceListResult', pipeline_response) + deserialized = self._deserialize("PeeringServiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -431,17 +824,69 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data + return ItemPaged(get_next, extract_data) + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServices"} # type: ignore + + @distributed_trace + def initialize_connection_monitor(self, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Initialize Peering Service for Connection Monitor functionality. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_initialize_connection_monitor_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.initialize_connection_monitor.metadata["url"], + headers=_headers, + params=_params, ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServices'} # type: ignore + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + initialize_connection_monitor.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/initializeConnectionMonitor"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peerings_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peerings_operations.py index 77ffd87bed49..79da4c544859 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peerings_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_peerings_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,356 +6,702 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(resource_group_name: str, peering_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, peering_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, peering_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, peering_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -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]] +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -class PeeringsOperations(object): - """PeeringsOperations operations. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerings") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PeeringsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`peerings` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def get( - self, - resource_group_name, # type: str - peering_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Peering" + @distributed_trace + def get(self, resource_group_name: str, peering_name: str, **kwargs: Any) -> _models.Peering: """Gets an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Peering, or the result of cls(response) + :return: Peering or the result of cls(response) :rtype: ~azure.mgmt.peering.models.Peering - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Peering"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - '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') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Peering] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + + @overload def create_or_update( self, - resource_group_name, # type: str - peering_name, # type: str - peering, # type: "_models.Peering" - **kwargs # type: Any - ): - # type: (...) -> "_models.Peering" + resource_group_name: str, + peering_name: str, + peering: _models.Peering, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: """Creates a new peering or updates an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str - :param peering: The properties needed to create or update a peering. + :param peering: The properties needed to create or update a peering. Required. :type peering: ~azure.mgmt.peering.models.Peering + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_name: str, + peering: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: + """Creates a new peering or updates an existing peering with the specified name under the given + subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param peering: The properties needed to create or update a peering. Required. + :type peering: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Peering, or the result of cls(response) + :return: Peering or the result of cls(response) :rtype: ~azure.mgmt.peering.models.Peering - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, resource_group_name: str, peering_name: str, peering: Union[_models.Peering, IO], **kwargs: Any + ) -> _models.Peering: + """Creates a new peering or updates an existing peering with the specified name under the given + subscription and resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param peering: The properties needed to create or update a peering. Is either a model type or + a IO type. Required. + :type peering: ~azure.mgmt.peering.models.Peering or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Peering"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - '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] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(peering, 'Peering') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Peering] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peering, (IO, bytes)): + _content = peering + else: + _json = self._serialize.body(peering, "Peering") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore - def delete( - self, - resource_group_name, # type: str - peering_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_name: str, **kwargs: Any + ) -> None: """Deletes an existing peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + @overload def update( self, - resource_group_name, # type: str - peering_name, # type: str - tags, # type: "_models.ResourceTags" - **kwargs # type: Any - ): - # type: (...) -> "_models.Peering" + resource_group_name: str, + peering_name: str, + tags: _models.ResourceTags, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: """Updates tags for a peering with the specified name under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_name: The name of the peering. + :param peering_name: The name of the peering. Required. :type peering_name: str - :param tags: The resource tags. + :param tags: The resource tags. Required. :type tags: ~azure.mgmt.peering.models.ResourceTags + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + peering_name: str, + tags: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Peering: + """Updates tags for a peering with the specified name under the given subscription and resource + group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param tags: The resource tags. Required. + :type tags: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Peering, or the result of cls(response) + :return: Peering or the result of cls(response) :rtype: ~azure.mgmt.peering.models.Peering - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, resource_group_name: str, peering_name: str, tags: Union[_models.ResourceTags, IO], **kwargs: Any + ) -> _models.Peering: + """Updates tags for a peering with the specified name under the given subscription and resource + group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param tags: The resource tags. Is either a model type or a IO type. Required. + :type tags: ~azure.mgmt.peering.models.ResourceTags or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Peering or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.Peering + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Peering"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), - '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] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(tags, 'ResourceTags') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Peering] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(tags, (IO, bytes)): + _content = tags + else: + _json = self._serialize.body(tags, "ResourceTags") + + request = build_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Peering', pipeline_response) + deserialized = self._deserialize("Peering", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}'} # type: ignore - def list_by_resource_group( - self, - resource_group_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringListResult"] + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}"} # type: ignore + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Peering"]: """Lists all of the peerings under the given subscription and resource group. - :param resource_group_name: The name of the resource group. + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Peering or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.Peering] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - '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_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringListResult', pipeline_response) + deserialized = self._deserialize("PeeringListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -363,66 +710,80 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings'} # type: ignore + return ItemPaged(get_next, extract_data) - def list_by_subscription( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringListResult"] + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings"} # type: ignore + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.Peering"]: """Lists all of the peerings under the given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Peering or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.Peering] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_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, + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringListResult', pipeline_response) + deserialized = self._deserialize("PeeringListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -431,17 +792,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerings'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Peering/peerings"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_prefixes_operations.py index 7979359a3cae..2c2b37cad585 100644 --- a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_prefixes_operations.py +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_prefixes_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,99 +6,569 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class PrefixesOperations(object): - """PrefixesOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_request( + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + subscription_id: str, + *, + expand: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.peering.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "prefixName": _SERIALIZER.url("prefix_name", prefix_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, peering_service_name: str, prefix_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "prefixName": _SERIALIZER.url("prefix_name", prefix_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, peering_service_name: str, prefix_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "prefixName": _SERIALIZER.url("prefix_name", prefix_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_peering_service_request( + resource_group_name: str, + peering_service_name: str, + subscription_id: str, + *, + expand: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringServiceName": _SERIALIZER.url("peering_service_name", peering_service_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`prefixes` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list_by_peering_service( + @distributed_trace + def get( self, - resource_group_name, # type: str - peering_service_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PeeringServicePrefixListResult"] - """Lists the peerings prefix in the resource group. - - :param resource_group_name: The resource group name. + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + expand: Optional[str] = None, + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Gets an existing prefix with the specified name under the given subscription, resource group + and peering service. + + :param resource_group_name: The name of the resource group. Required. :type resource_group_name: str - :param peering_service_name: The peering service name. + :param peering_service_name: The name of the peering service. Required. :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param expand: The properties to be expanded. Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PeeringServicePrefixListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServicePrefixListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefixListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-08-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServicePrefix] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + prefix_name=prefix_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringServicePrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}"} # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + peering_service_prefix: _models.PeeringServicePrefix, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Creates a new prefix with the specified name under the given subscription, resource group and + peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param peering_service_prefix: The properties needed to create a prefix. Required. + :type peering_service_prefix: ~azure.mgmt.peering.models.PeeringServicePrefix + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + peering_service_prefix: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Creates a new prefix with the specified name under the given subscription, resource group and + peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param peering_service_prefix: The properties needed to create a prefix. Required. + :type peering_service_prefix: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + peering_service_name: str, + prefix_name: str, + peering_service_prefix: Union[_models.PeeringServicePrefix, IO], + **kwargs: Any + ) -> _models.PeeringServicePrefix: + """Creates a new prefix with the specified name under the given subscription, resource group and + peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :param peering_service_prefix: The properties needed to create a prefix. Is either a model type + or a IO type. Required. + :type peering_service_prefix: ~azure.mgmt.peering.models.PeeringServicePrefix or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringServicePrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServicePrefix] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(peering_service_prefix, (IO, bytes)): + _content = peering_service_prefix + else: + _json = self._serialize.body(peering_service_prefix, "PeeringServicePrefix") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + prefix_name=prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PeeringServicePrefix", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PeeringServicePrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_service_name: str, prefix_name: str, **kwargs: Any + ) -> None: + """Deletes an existing prefix with the specified name under the given subscription, resource group + and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param prefix_name: The name of the prefix. Required. + :type prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + prefix_name=prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}"} # type: ignore + + @distributed_trace + def list_by_peering_service( + self, resource_group_name: str, peering_service_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.PeeringServicePrefix"]: + """Lists all prefixes under the given subscription, resource group and peering service. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_service_name: The name of the peering service. Required. + :type peering_service_name: str + :param expand: The properties to be expanded. Default value is None. + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringServicePrefix or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringServicePrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringServicePrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): if not next_link: - # Construct URL - url = self.list_by_peering_service.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), - '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_peering_service_request( + resource_group_name=resource_group_name, + peering_service_name=peering_service_name, + subscription_id=self._config.subscription_id, + expand=expand, + api_version=api_version, + template_url=self.list_by_peering_service.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PeeringServicePrefixListResult', pipeline_response) + deserialized = self._deserialize("PeeringServicePrefixListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -106,17 +577,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_peering_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_peering_service.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_received_routes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_received_routes_operations.py new file mode 100644 index 000000000000..49045fa25995 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_received_routes_operations.py @@ -0,0 +1,233 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_peering_request( + resource_group_name: str, + peering_name: str, + subscription_id: str, + *, + prefix: Optional[str] = None, + as_path: Optional[str] = None, + origin_as_validation_state: Optional[str] = None, + rpki_validation_state: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/receivedRoutes", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if prefix is not None: + _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") + if as_path is not None: + _params["asPath"] = _SERIALIZER.query("as_path", as_path, "str") + if origin_as_validation_state is not None: + _params["originAsValidationState"] = _SERIALIZER.query( + "origin_as_validation_state", origin_as_validation_state, "str" + ) + if rpki_validation_state is not None: + _params["rpkiValidationState"] = _SERIALIZER.query("rpki_validation_state", rpki_validation_state, "str") + if skip_token is not None: + _params["$skipToken"] = _SERIALIZER.query("skip_token", skip_token, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ReceivedRoutesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`received_routes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_peering( + self, + resource_group_name: str, + peering_name: str, + prefix: Optional[str] = None, + as_path: Optional[str] = None, + origin_as_validation_state: Optional[str] = None, + rpki_validation_state: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.PeeringReceivedRoute"]: + """Lists the prefixes received over the specified peering under the given subscription and + resource group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param prefix: The optional prefix that can be used to filter the routes. Default value is + None. + :type prefix: str + :param as_path: The optional AS path that can be used to filter the routes. Default value is + None. + :type as_path: str + :param origin_as_validation_state: The optional origin AS validation state that can be used to + filter the routes. Default value is None. + :type origin_as_validation_state: str + :param rpki_validation_state: The optional RPKI validation state that can be used to filter the + routes. Default value is None. + :type rpki_validation_state: str + :param skip_token: The optional page continuation token that is used in the event of paginated + result. Default value is None. + :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 PeeringReceivedRoute or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringReceivedRoute] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringReceivedRouteListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + prefix=prefix, + as_path=as_path, + origin_as_validation_state=origin_as_validation_state, + rpki_validation_state=rpki_validation_state, + skip_token=skip_token, + api_version=api_version, + template_url=self.list_by_peering.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringReceivedRouteListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_peering.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/receivedRoutes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_registered_asns_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_registered_asns_operations.py new file mode 100644 index 000000000000..a8740a0e4617 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_registered_asns_operations.py @@ -0,0 +1,568 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request( + resource_group_name: str, peering_name: str, registered_asn_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "registeredAsnName": _SERIALIZER.url("registered_asn_name", registered_asn_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, peering_name: str, registered_asn_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "registeredAsnName": _SERIALIZER.url("registered_asn_name", registered_asn_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, peering_name: str, registered_asn_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "registeredAsnName": _SERIALIZER.url("registered_asn_name", registered_asn_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_peering_request( + resource_group_name: str, peering_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RegisteredAsnsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`registered_asns` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, peering_name: str, registered_asn_name: str, **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Gets an existing registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the registered ASN. Required. + :type registered_asn_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredAsn] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_asn_name=registered_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringRegisteredAsn", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}"} # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_asn_name: str, + registered_asn: _models.PeeringRegisteredAsn, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Creates a new registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the ASN. Required. + :type registered_asn_name: str + :param registered_asn: The properties needed to create a registered ASN. Required. + :type registered_asn: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_asn_name: str, + registered_asn: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Creates a new registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the ASN. Required. + :type registered_asn_name: str + :param registered_asn: The properties needed to create a registered ASN. Required. + :type registered_asn: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_asn_name: str, + registered_asn: Union[_models.PeeringRegisteredAsn, IO], + **kwargs: Any + ) -> _models.PeeringRegisteredAsn: + """Creates a new registered ASN with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the ASN. Required. + :type registered_asn_name: str + :param registered_asn: The properties needed to create a registered ASN. Is either a model type + or a IO type. Required. + :type registered_asn: ~azure.mgmt.peering.models.PeeringRegisteredAsn or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredAsn or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredAsn + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredAsn] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(registered_asn, (IO, bytes)): + _content = registered_asn + else: + _json = self._serialize.body(registered_asn, "PeeringRegisteredAsn") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_asn_name=registered_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PeeringRegisteredAsn", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PeeringRegisteredAsn", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_name: str, registered_asn_name: str, **kwargs: Any + ) -> None: + """Deletes an existing registered ASN with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_asn_name: The name of the registered ASN. Required. + :type registered_asn_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_asn_name=registered_asn_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns/{registeredAsnName}"} # type: ignore + + @distributed_trace + def list_by_peering( + self, resource_group_name: str, peering_name: str, **kwargs: Any + ) -> Iterable["_models.PeeringRegisteredAsn"]: + """Lists all registered ASNs under the given subscription, resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringRegisteredAsn or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringRegisteredAsn] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredAsnListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_peering.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringRegisteredAsnListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_peering.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredAsns"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_registered_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_registered_prefixes_operations.py new file mode 100644 index 000000000000..38bd0d6b50c4 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_registered_prefixes_operations.py @@ -0,0 +1,667 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request( + resource_group_name: str, peering_name: str, registered_prefix_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "registeredPrefixName": _SERIALIZER.url("registered_prefix_name", registered_prefix_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, peering_name: str, registered_prefix_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "registeredPrefixName": _SERIALIZER.url("registered_prefix_name", registered_prefix_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, peering_name: str, registered_prefix_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "registeredPrefixName": _SERIALIZER.url("registered_prefix_name", registered_prefix_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_peering_request( + resource_group_name: str, peering_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_validate_request( + resource_group_name: str, peering_name: str, registered_prefix_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}/validate", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "registeredPrefixName": _SERIALIZER.url("registered_prefix_name", registered_prefix_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class RegisteredPrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`registered_prefixes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, peering_name: str, registered_prefix_name: str, **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Gets an existing registered prefix with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefix] + + request = build_get_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}"} # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_prefix_name: str, + registered_prefix: _models.PeeringRegisteredPrefix, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Creates a new registered prefix with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :param registered_prefix: The properties needed to create a registered prefix. Required. + :type registered_prefix: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_prefix_name: str, + registered_prefix: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Creates a new registered prefix with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :param registered_prefix: The properties needed to create a registered prefix. Required. + :type registered_prefix: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + peering_name: str, + registered_prefix_name: str, + registered_prefix: Union[_models.PeeringRegisteredPrefix, IO], + **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Creates a new registered prefix with the specified name under the given subscription, resource + group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :param registered_prefix: The properties needed to create a registered prefix. Is either a + model type or a IO type. Required. + :type registered_prefix: ~azure.mgmt.peering.models.PeeringRegisteredPrefix or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefix] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(registered_prefix, (IO, bytes)): + _content = registered_prefix + else: + _json = self._serialize.body(registered_prefix, "PeeringRegisteredPrefix") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, peering_name: str, registered_prefix_name: str, **kwargs: Any + ) -> None: + """Deletes an existing registered prefix with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}"} # type: ignore + + @distributed_trace + def list_by_peering( + self, resource_group_name: str, peering_name: str, **kwargs: Any + ) -> Iterable["_models.PeeringRegisteredPrefix"]: + """Lists all registered prefixes under the given subscription, resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either PeeringRegisteredPrefix or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.PeeringRegisteredPrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_peering_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_peering.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PeeringRegisteredPrefixListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_peering.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes"} # type: ignore + + @distributed_trace + def validate( + self, resource_group_name: str, peering_name: str, registered_prefix_name: str, **kwargs: Any + ) -> _models.PeeringRegisteredPrefix: + """Validates an existing registered prefix with the specified name under the given subscription, + resource group and peering. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param peering_name: The name of the peering. Required. + :type peering_name: str + :param registered_prefix_name: The name of the registered prefix. Required. + :type registered_prefix_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PeeringRegisteredPrefix or the result of cls(response) + :rtype: ~azure.mgmt.peering.models.PeeringRegisteredPrefix + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PeeringRegisteredPrefix] + + request = build_validate_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + registered_prefix_name=registered_prefix_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PeeringRegisteredPrefix", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + validate.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/registeredPrefixes/{registeredPrefixName}/validate"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_rp_unbilled_prefixes_operations.py b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_rp_unbilled_prefixes_operations.py new file mode 100644 index 000000000000..2d86705672d2 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/azure/mgmt/peering/operations/_rp_unbilled_prefixes_operations.py @@ -0,0 +1,192 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import PeeringManagementClientMixinABC, _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + resource_group_name: str, + peering_name: str, + subscription_id: str, + *, + consolidate: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/rpUnbilledPrefixes", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "peeringName": _SERIALIZER.url("peering_name", peering_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if consolidate is not None: + _params["consolidate"] = _SERIALIZER.query("consolidate", consolidate, "bool") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class RpUnbilledPrefixesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.peering.PeeringManagementClient`'s + :attr:`rp_unbilled_prefixes` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, peering_name: str, consolidate: Optional[bool] = None, **kwargs: Any + ) -> Iterable["_models.RpUnbilledPrefix"]: + """Lists all of the RP unbilled prefixes for the specified peering. + + :param resource_group_name: The Azure resource group name. Required. + :type resource_group_name: str + :param peering_name: The peering name. Required. + :type peering_name: str + :param consolidate: Flag to enable consolidation prefixes. Default value is None. + :type consolidate: bool + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RpUnbilledPrefix or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.peering.models.RpUnbilledPrefix] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RpUnbilledPrefixListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + resource_group_name=resource_group_name, + peering_name=peering_name, + subscription_id=self._config.subscription_id, + consolidate=consolidate, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RpUnbilledPrefixListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peerings/{peeringName}/rpUnbilledPrefixes"} # type: ignore diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/call_looking_glass_to_execute_a_command.py b/sdk/peering/azure-mgmt-peering/generated_samples/call_looking_glass_to_execute_a_command.py new file mode 100644 index 000000000000..8cb93e209ae6 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/call_looking_glass_to_execute_a_command.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python call_looking_glass_to_execute_a_command.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.looking_glass.invoke( + command="Traceroute", + source_type="AzureRegion", + source_location="West US", + destination_ip="0.0.0.0", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/LookingGlassInvokeCommand.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/check_if_peering_service_provider_is_available_in_customer_location.py b/sdk/peering/azure-mgmt-peering/generated_samples/check_if_peering_service_provider_is_available_in_customer_location.py new file mode 100644 index 000000000000..2efc125ed2cf --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/check_if_peering_service_provider_is_available_in_customer_location.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python check_if_peering_service_provider_is_available_in_customer_location.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.check_service_provider_availability( + check_service_provider_availability_input={ + "peeringServiceLocation": "peeringServiceLocation1", + "peeringServiceProvider": "peeringServiceProvider1", + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CheckServiceProviderAvailability.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_a_direct_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_direct_peering.py new file mode 100644 index 000000000000..47e28e3fd6fb --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_direct_peering.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_a_direct_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.create_or_update( + resource_group_name="rgName", + peering_name="peeringName", + peering={ + "kind": "Direct", + "location": "eastus", + "properties": { + "direct": { + "connections": [ + { + "bandwidthInMbps": 10000, + "bgpSession": { + "maxPrefixesAdvertisedV4": 1000, + "maxPrefixesAdvertisedV6": 100, + "md5AuthenticationKey": "test-md5-auth-key", + "sessionPrefixV4": "192.168.0.0/31", + "sessionPrefixV6": "fd00::0/127", + }, + "connectionIdentifier": "5F4CB5C7-6B43-4444-9338-9ABC72606C16", + "peeringDBFacilityId": 99999, + "sessionAddressProvider": "Peer", + "useForPeeringService": False, + }, + { + "bandwidthInMbps": 10000, + "connectionIdentifier": "8AB00818-D533-4504-A25A-03A17F61201C", + "peeringDBFacilityId": 99999, + "sessionAddressProvider": "Microsoft", + "useForPeeringService": True, + }, + ], + "directPeeringType": "Edge", + "peerAsn": {"id": "/subscriptions/subId/providers/Microsoft.Peering/peerAsns/myAsn1"}, + }, + "peeringLocation": "peeringLocation0", + }, + "sku": {"name": "Basic_Direct_Free"}, + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreateDirectPeering.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peer_asn.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peer_asn.py new file mode 100644 index 000000000000..0efa203fe5e1 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peer_asn.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_a_peer_asn.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peer_asns.create_or_update( + peer_asn_name="peerAsnName", + peer_asn={ + "properties": { + "peerAsn": 65000, + "peerContactDetail": [ + {"email": "noc@contoso.com", "phone": "+1 (234) 567-8999", "role": "Noc"}, + {"email": "abc@contoso.com", "phone": "+1 (234) 567-8900", "role": "Policy"}, + {"email": "xyz@contoso.com", "phone": "+1 (234) 567-8900", "role": "Technical"}, + ], + "peerName": "Contoso", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreatePeerAsn.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peering_service.py new file mode 100644 index 000000000000..c4fa05e59534 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peering_service.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_a_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_services.create_or_update( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + peering_service={ + "location": "eastus", + "properties": { + "peeringServiceLocation": "state1", + "peeringServiceProvider": "serviceProvider1", + "providerBackupPeeringLocation": "peeringLocation2", + "providerPrimaryPeeringLocation": "peeringLocation1", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreatePeeringService.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peering_with_exchange_route_server.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peering_with_exchange_route_server.py new file mode 100644 index 000000000000..34164bf59af8 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_a_peering_with_exchange_route_server.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_a_peering_with_exchange_route_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.create_or_update( + resource_group_name="rgName", + peering_name="peeringName", + peering={ + "kind": "Direct", + "location": "eastus", + "properties": { + "direct": { + "connections": [ + { + "bandwidthInMbps": 10000, + "bgpSession": { + "maxPrefixesAdvertisedV4": 1000, + "maxPrefixesAdvertisedV6": 100, + "microsoftSessionIPv4Address": "192.168.0.123", + "peerSessionIPv4Address": "192.168.0.234", + "sessionPrefixV4": "192.168.0.0/24", + }, + "connectionIdentifier": "5F4CB5C7-6B43-4444-9338-9ABC72606C16", + "peeringDBFacilityId": 99999, + "sessionAddressProvider": "Peer", + "useForPeeringService": True, + } + ], + "directPeeringType": "IxRs", + "peerAsn": {"id": "/subscriptions/subId/providers/Microsoft.Peering/peerAsns/myAsn1"}, + }, + "peeringLocation": "peeringLocation0", + }, + "sku": {"name": "Premium_Direct_Free"}, + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreatePeeringWithExchangeRouteServer.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_an_exchange_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_an_exchange_peering.py new file mode 100644 index 000000000000..509f5643867f --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_an_exchange_peering.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_an_exchange_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.create_or_update( + resource_group_name="rgName", + peering_name="peeringName", + peering={ + "kind": "Exchange", + "location": "eastus", + "properties": { + "exchange": { + "connections": [ + { + "bgpSession": { + "maxPrefixesAdvertisedV4": 1000, + "maxPrefixesAdvertisedV6": 100, + "md5AuthenticationKey": "test-md5-auth-key", + "peerSessionIPv4Address": "192.168.2.1", + "peerSessionIPv6Address": "fd00::1", + }, + "connectionIdentifier": "CE495334-0E94-4E51-8164-8116D6CD284D", + "peeringDBFacilityId": 99999, + }, + { + "bgpSession": { + "maxPrefixesAdvertisedV4": 1000, + "maxPrefixesAdvertisedV6": 100, + "md5AuthenticationKey": "test-md5-auth-key", + "peerSessionIPv4Address": "192.168.2.2", + "peerSessionIPv6Address": "fd00::2", + }, + "connectionIdentifier": "CDD8E673-CB07-47E6-84DE-3739F778762B", + "peeringDBFacilityId": 99999, + }, + ], + "peerAsn": {"id": "/subscriptions/subId/providers/Microsoft.Peering/peerAsns/myAsn1"}, + }, + "peeringLocation": "peeringLocation0", + }, + "sku": {"name": "Basic_Exchange_Free"}, + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreateExchangePeering.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_prefix_for_the_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_prefix_for_the_peering_service.py new file mode 100644 index 000000000000..7b00306d6acc --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_prefix_for_the_peering_service.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_or_update_a_prefix_for_the_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.prefixes.create_or_update( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + prefix_name="peeringServicePrefixName", + peering_service_prefix={ + "properties": { + "peeringServicePrefixKey": "00000000-0000-0000-0000-000000000000", + "prefix": "192.168.1.0/24", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreatePeeringServicePrefix.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_registered_asn_for_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_registered_asn_for_the_peering.py new file mode 100644 index 000000000000..82e245fa974c --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_registered_asn_for_the_peering.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_or_update_a_registered_asn_for_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_asns.create_or_update( + resource_group_name="rgName", + peering_name="peeringName", + registered_asn_name="registeredAsnName", + registered_asn={"properties": {"asn": 65000}}, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreateRegisteredAsn.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_registered_prefix_for_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_registered_prefix_for_the_peering.py new file mode 100644 index 000000000000..7bd3f05b15e1 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_a_registered_prefix_for_the_peering.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_or_update_a_registered_prefix_for_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_prefixes.create_or_update( + resource_group_name="rgName", + peering_name="peeringName", + registered_prefix_name="registeredPrefixName", + registered_prefix={"properties": {"prefix": "10.22.20.0/24"}}, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreateRegisteredPrefix.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_connection_monitor_test.py b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_connection_monitor_test.py new file mode 100644 index 000000000000..88b04ceab5fc --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/create_or_update_connection_monitor_test.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python create_or_update_connection_monitor_test.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.connection_monitor_tests.create_or_update( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + connection_monitor_test_name="connectionMonitorTestName", + connection_monitor_test={ + "properties": { + "destination": "Example Destination", + "destinationPort": 443, + "sourceAgent": "Example Source Agent", + "testFrequencyInSec": 30, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/CreateOrUpdateConnectionMonitorTest.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peer_asn.py b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peer_asn.py new file mode 100644 index 000000000000..885d2ba0d532 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peer_asn.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python delete_a_peer_asn.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peer_asns.delete( + peer_asn_name="peerAsnName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/DeletePeerAsn.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peering.py new file mode 100644 index 000000000000..4e7565cb20c1 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peering.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python delete_a_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.delete( + resource_group_name="rgName", + peering_name="peeringName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/DeletePeering.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peering_service.py new file mode 100644 index 000000000000..39defc38f23f --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_peering_service.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python delete_a_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_services.delete( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/DeletePeeringService.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_prefix_associated_with_the_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_prefix_associated_with_the_peering_service.py new file mode 100644 index 000000000000..03c9f68991ac --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/delete_a_prefix_associated_with_the_peering_service.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python delete_a_prefix_associated_with_the_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.prefixes.delete( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + prefix_name="peeringServicePrefixName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/DeletePeeringServicePrefix.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/delete_connection_monitor_test.py b/sdk/peering/azure-mgmt-peering/generated_samples/delete_connection_monitor_test.py new file mode 100644 index 000000000000..a8adb1c1f35e --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/delete_connection_monitor_test.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python delete_connection_monitor_test.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.connection_monitor_tests.delete( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + connection_monitor_test_name="connectionMonitorTestName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/DeleteConnectionMonitorTest.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/deletes_a_registered_asn_associated_with_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/deletes_a_registered_asn_associated_with_the_peering.py new file mode 100644 index 000000000000..cf171437a1ee --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/deletes_a_registered_asn_associated_with_the_peering.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python deletes_a_registered_asn_associated_with_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_asns.delete( + resource_group_name="rgName", + peering_name="peeringName", + registered_asn_name="registeredAsnName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/DeleteRegisteredAsn.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/deletes_a_registered_prefix_associated_with_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/deletes_a_registered_prefix_associated_with_the_peering.py new file mode 100644 index 000000000000..543cbfb7f910 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/deletes_a_registered_prefix_associated_with_the_peering.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python deletes_a_registered_prefix_associated_with_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_prefixes.delete( + resource_group_name="rgName", + peering_name="peeringName", + registered_prefix_name="registeredPrefixName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/DeleteRegisteredPrefix.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peer_asn.py b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peer_asn.py new file mode 100644 index 000000000000..9ce13c67c972 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peer_asn.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python get_a_peer_asn.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peer_asns.get( + peer_asn_name="peerAsnName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetPeerAsn.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peering.py new file mode 100644 index 000000000000..c037fb0e1bd8 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peering.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python get_a_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.get( + resource_group_name="rgName", + peering_name="peeringName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetPeering.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peering_service.py new file mode 100644 index 000000000000..6b5ee0daa275 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_peering_service.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python get_a_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_services.get( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetPeeringService.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/get_a_prefix_associated_with_the_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_prefix_associated_with_the_peering_service.py new file mode 100644 index 000000000000..90c5320f7562 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_prefix_associated_with_the_peering_service.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python get_a_prefix_associated_with_the_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.prefixes.get( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + prefix_name="peeringServicePrefixName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetPeeringServicePrefix.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/get_a_registered_asn_associated_with_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_registered_asn_associated_with_the_peering.py new file mode 100644 index 000000000000..fb5441af520d --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_registered_asn_associated_with_the_peering.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python get_a_registered_asn_associated_with_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_asns.get( + resource_group_name="rgName", + peering_name="peeringName", + registered_asn_name="registeredAsnName0", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetRegisteredAsn.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/get_a_registered_prefix_associated_with_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_registered_prefix_associated_with_the_peering.py new file mode 100644 index 000000000000..ed00d7c69155 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/get_a_registered_prefix_associated_with_the_peering.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python get_a_registered_prefix_associated_with_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_prefixes.get( + resource_group_name="rgName", + peering_name="peeringName", + registered_prefix_name="registeredPrefixName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetRegisteredPrefix.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/get_connection_monitor_test.py b/sdk/peering/azure-mgmt-peering/generated_samples/get_connection_monitor_test.py new file mode 100644 index 000000000000..3a7423ccf445 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/get_connection_monitor_test.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python get_connection_monitor_test.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.connection_monitor_tests.get( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + connection_monitor_test_name="connectionMonitorTestName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetConnectionMonitorTest.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/initialize_peering_service_for_connection_monitor_functionality.py b/sdk/peering/azure-mgmt-peering/generated_samples/initialize_peering_service_for_connection_monitor_functionality.py new file mode 100644 index 000000000000..1cabbd0d47c3 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/initialize_peering_service_for_connection_monitor_functionality.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python initialize_peering_service_for_connection_monitor_functionality.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_services.initialize_connection_monitor() + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/InitializeConnectionMonitor.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_all_connection_monitor_tests_associated_with_the_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_connection_monitor_tests_associated_with_the_peering_service.py new file mode 100644 index 000000000000..1885f2181792 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_connection_monitor_tests_associated_with_the_peering_service.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_all_connection_monitor_tests_associated_with_the_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.connection_monitor_tests.list_by_peering_service( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListConnectionMonitorTestsByPeeringService.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_cdn_peering_prefixes_advertised_at_a_particular_peering_location.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_cdn_peering_prefixes_advertised_at_a_particular_peering_location.py new file mode 100644 index 000000000000..69726c0e05b3 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_cdn_peering_prefixes_advertised_at_a_particular_peering_location.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_all_the_cdn_peering_prefixes_advertised_at_a_particular_peering_location.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.cdn_peering_prefixes.list( + peering_location="peeringLocation0", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListCdnPeeringPrefixes.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_prefixes_associated_with_the_peering_service.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_prefixes_associated_with_the_peering_service.py new file mode 100644 index 000000000000..cc5bfb20e6dd --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_prefixes_associated_with_the_peering_service.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_all_the_prefixes_associated_with_the_peering_service.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.prefixes.list_by_peering_service( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPrefixesByPeeringService.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_registered_as_ns_associated_with_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_registered_as_ns_associated_with_the_peering.py new file mode 100644 index 000000000000..ae702a79dca3 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_registered_as_ns_associated_with_the_peering.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_all_the_registered_as_ns_associated_with_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_asns.list_by_peering( + resource_group_name="rgName", + peering_name="peeringName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListRegisteredAsnsByPeering.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_registered_prefixes_associated_with_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_registered_prefixes_associated_with_the_peering.py new file mode 100644 index 000000000000..5128663b4312 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_registered_prefixes_associated_with_the_peering.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_all_the_registered_prefixes_associated_with_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_prefixes.list_by_peering( + resource_group_name="rgName", + peering_name="peeringName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListRegisteredPrefixesByPeering.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_rp_unbilled_prefixes_advertised_at_a_particular_peering_location.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_rp_unbilled_prefixes_advertised_at_a_particular_peering_location.py new file mode 100644 index 000000000000..a586e5d4ec5c --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_all_the_rp_unbilled_prefixes_advertised_at_a_particular_peering_location.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_all_the_rp_unbilled_prefixes_advertised_at_a_particular_peering_location.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.rp_unbilled_prefixes.list( + resource_group_name="rgName", + peering_name="peeringName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListRpUnbilledPrefixes.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_direct_peering_locations.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_direct_peering_locations.py new file mode 100644 index 000000000000..af1f551723ae --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_direct_peering_locations.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_direct_peering_locations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_locations.list( + kind="Direct", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListDirectPeeringLocations.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_exchange_peering_locations.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_exchange_peering_locations.py new file mode 100644 index 000000000000..3567de4ba60d --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_exchange_peering_locations.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_exchange_peering_locations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_locations.list( + kind="Exchange", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListExchangePeeringLocations.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_legacy_peerings.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_legacy_peerings.py new file mode 100644 index 000000000000..954fecd5ef7e --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_legacy_peerings.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_legacy_peerings.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.legacy_peerings.list( + peering_location="peeringLocation0", + kind="Exchange", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListLegacyPeerings.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peer_as_ns_in_a_subscription.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peer_as_ns_in_a_subscription.py new file mode 100644 index 000000000000..adb44974f42f --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peer_as_ns_in_a_subscription.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peer_as_ns_in_a_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peer_asns.list_by_subscription() + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeerAsnsBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_operations.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_operations.py new file mode 100644 index 000000000000..f3ce267ea9b5 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_operations.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peering_operations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.operations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringOperations.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_countries.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_countries.py new file mode 100644 index 000000000000..9f78ec4a2f4b --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_countries.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peering_service_countries.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_service_countries.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringServiceCountriesBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_locations.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_locations.py new file mode 100644 index 000000000000..69d75c3a44b4 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_locations.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peering_service_locations.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_service_locations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringServiceLocationsBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_providers.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_providers.py new file mode 100644 index 000000000000..38ce5268a4d7 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_service_providers.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peering_service_providers.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_service_providers.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringServiceProviders.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_services_in_a_resource_group.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_services_in_a_resource_group.py new file mode 100644 index 000000000000..287c2d129451 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_services_in_a_resource_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peering_services_in_a_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_services.list_by_resource_group( + resource_group_name="rgName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringServicesByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_services_in_a_subscription.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_services_in_a_subscription.py new file mode 100644 index 000000000000..4e64c3c21925 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peering_services_in_a_subscription.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peering_services_in_a_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_services.list_by_subscription() + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringServicesBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peerings_in_a_resource_group.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peerings_in_a_resource_group.py new file mode 100644 index 000000000000..bf7edec55eaf --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peerings_in_a_resource_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peerings_in_a_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.list_by_resource_group( + resource_group_name="rgName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringsByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/list_peerings_in_a_subscription.py b/sdk/peering/azure-mgmt-peering/generated_samples/list_peerings_in_a_subscription.py new file mode 100644 index 000000000000..276267306b37 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/list_peerings_in_a_subscription.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python list_peerings_in_a_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.list_by_subscription() + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ListPeeringsBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/lists_the_prefixes_received_over_the_specified_peering_under_the_given_subscription_and_resource_group..py b/sdk/peering/azure-mgmt-peering/generated_samples/lists_the_prefixes_received_over_the_specified_peering_under_the_given_subscription_and_resource_group..py new file mode 100644 index 000000000000..1c07f9d7f3a6 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/lists_the_prefixes_received_over_the_specified_peering_under_the_given_subscription_and_resource_group..py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python lists_the_prefixes_received_over_the_specified_peering_under_the_given_subscription_and_resource_group..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.received_routes.list_by_peering( + resource_group_name="rgName", + peering_name="peeringName", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/GetPeeringReceivedRoutes.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/update_peering_service_tags.py b/sdk/peering/azure-mgmt-peering/generated_samples/update_peering_service_tags.py new file mode 100644 index 000000000000..4967f7ecb8a5 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/update_peering_service_tags.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python update_peering_service_tags.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peering_services.update( + resource_group_name="rgName", + peering_service_name="peeringServiceName", + tags={"tags": {"tag0": "value0", "tag1": "value1"}}, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/UpdatePeeringServiceTags.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/update_peering_tags.py b/sdk/peering/azure-mgmt-peering/generated_samples/update_peering_tags.py new file mode 100644 index 000000000000..2fd6c8ab5f02 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/update_peering_tags.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python update_peering_tags.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.peerings.update( + resource_group_name="rgName", + peering_name="peeringName", + tags={"tags": {"tag0": "value0", "tag1": "value1"}}, + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/UpdatePeeringTags.json +if __name__ == "__main__": + main() diff --git a/sdk/peering/azure-mgmt-peering/generated_samples/validate_a_registered_prefix_associated_with_the_peering.py b/sdk/peering/azure-mgmt-peering/generated_samples/validate_a_registered_prefix_associated_with_the_peering.py new file mode 100644 index 000000000000..53e8e4c5c0f7 --- /dev/null +++ b/sdk/peering/azure-mgmt-peering/generated_samples/validate_a_registered_prefix_associated_with_the_peering.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.peering import PeeringManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-peering +# USAGE + python validate_a_registered_prefix_associated_with_the_peering.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PeeringManagementClient( + credential=DefaultAzureCredential(), + subscription_id="subId", + ) + + response = client.registered_prefixes.validate( + resource_group_name="rgName", + peering_name="peeringName", + registered_prefix_name="registeredPrefixName", + ) + print(response) + + +# x-ms-original-file: specification/peering/resource-manager/Microsoft.Peering/stable/2022-10-01/examples/ValidateRegisteredPrefix.json +if __name__ == "__main__": + main()