diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/_meta.json b/sdk/containerinstance/azure-mgmt-containerinstance/_meta.json index 4cba02a2cded..2e5f2d9e6463 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/_meta.json +++ b/sdk/containerinstance/azure-mgmt-containerinstance/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "autorest": "3.8.4", "use": [ - "@autorest/python@5.12.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.0.1", + "@autorest/modelerfour@4.23.5" ], - "commit": "5dad3b83d0926768ede15ed41895d5f38defd512", + "commit": "d90e6faa2b5242f43ebcb053abaa25990a7387cf", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/containerinstance/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --track2 --use=@autorest/python@5.12.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/containerinstance/resource-manager/readme.md --models-mode=msrest --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.0.1 --use=@autorest/modelerfour@4.23.5 --version=3.8.4 --version-tolerant=False", "readme": "specification/containerinstance/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/__init__.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/__init__.py index ee4609bc2aba..4092feba59b9 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/__init__.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/__init__.py @@ -10,9 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['ContainerInstanceManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +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__ = ["ContainerInstanceManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_configuration.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_configuration.py index 0f0b36953cde..7b3658ca189f 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_configuration.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_configuration.py @@ -19,25 +19,26 @@ from azure.core.credentials import TokenCredential -class ContainerInstanceManagementClientConfiguration(Configuration): +class ContainerInstanceManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for ContainerInstanceManagementClient. 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: Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: Subscription credentials which uniquely identify Microsoft Azure + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(ContainerInstanceManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,24 +46,25 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-10-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-containerinstance/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-containerinstance/{}".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 = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_container_instance_management_client.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_container_instance_management_client.py index b127cd6868b8..a513e394027f 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_container_instance_management_client.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_container_instance_management_client.py @@ -7,21 +7,28 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING +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 ContainerInstanceManagementClientConfiguration -from .operations import ContainerGroupsOperations, ContainersOperations, LocationOperations, Operations +from ._serialization import Deserializer, Serializer +from .operations import ( + ContainerGroupsOperations, + ContainersOperations, + LocationOperations, + Operations, + SubnetServiceAssociationLinkOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class ContainerInstanceManagementClient: + +class ContainerInstanceManagementClient: # pylint: disable=client-accepts-api-version-keyword """ContainerInstanceManagementClient. :ivar container_groups: ContainerGroupsOperations operations @@ -32,13 +39,19 @@ class ContainerInstanceManagementClient: :vartype location: azure.mgmt.containerinstance.operations.LocationOperations :ivar containers: ContainersOperations operations :vartype containers: azure.mgmt.containerinstance.operations.ContainersOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar subnet_service_association_link: SubnetServiceAssociationLinkOperations operations + :vartype subnet_service_association_link: + azure.mgmt.containerinstance.operations.SubnetServiceAssociationLinkOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: Subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :param base_url: Service URL. Default value is 'https://management.azure.com'. + :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ @@ -50,24 +63,26 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = ContainerInstanceManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = ContainerInstanceManagementClientConfiguration( + 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._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.container_groups = ContainerGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.container_groups = ContainerGroupsOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.location = LocationOperations(self._client, self._config, self._serialize, self._deserialize) self.containers = ContainersOperations(self._client, self._config, self._serialize, self._deserialize) + self.subnet_service_association_link = SubnetServiceAssociationLinkOperations( + self._client, self._config, self._serialize, self._deserialize + ) - - def _send_request( - self, - request, # type: HttpRequest - **kwargs: Any - ) -> HttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -76,7 +91,7 @@ def _send_request( >>> response = client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + 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 diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_patch.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_patch.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_serialization.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_serialization.py new file mode 100644 index 000000000000..648f84cc4e65 --- /dev/null +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_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.warning( + "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/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_vendor.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_vendor.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_vendor.py @@ -7,6 +7,7 @@ from azure.core.pipeline.transport import HttpRequest + def _convert_request(request, files=None): data = request.content if not files else None request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) @@ -14,6 +15,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -21,7 +23,5 @@ def _format_url_section(template, **kwargs): 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 - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_version.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_version.py index 6b357123854d..e5754a47ce68 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_version.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "9.2.0" +VERSION = "1.0.0b1" diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/__init__.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/__init__.py index 15e3f49794f2..8c41a131d6dc 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/__init__.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/__init__.py @@ -7,9 +7,15 @@ # -------------------------------------------------------------------------- from ._container_instance_management_client import ContainerInstanceManagementClient -__all__ = ['ContainerInstanceManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +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__ = ["ContainerInstanceManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_configuration.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_configuration.py index abc55271157b..d2fa11786de1 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_configuration.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_configuration.py @@ -19,25 +19,26 @@ from azure.core.credentials_async import AsyncTokenCredential -class ContainerInstanceManagementClientConfiguration(Configuration): +class ContainerInstanceManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for ContainerInstanceManagementClient. 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: Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: Subscription credentials which uniquely identify Microsoft Azure + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2021-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(ContainerInstanceManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,23 +46,22 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-10-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-containerinstance/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-containerinstance/{}".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 = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_container_instance_management_client.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_container_instance_management_client.py index 8018736f8395..80e4cdf6db43 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_container_instance_management_client.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_container_instance_management_client.py @@ -7,21 +7,28 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING +from typing import Any, Awaitable, TYPE_CHECKING 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 ContainerInstanceManagementClientConfiguration -from .operations import ContainerGroupsOperations, ContainersOperations, LocationOperations, Operations +from .operations import ( + ContainerGroupsOperations, + ContainersOperations, + LocationOperations, + Operations, + SubnetServiceAssociationLinkOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class ContainerInstanceManagementClient: + +class ContainerInstanceManagementClient: # pylint: disable=client-accepts-api-version-keyword """ContainerInstanceManagementClient. :ivar container_groups: ContainerGroupsOperations operations @@ -33,13 +40,19 @@ class ContainerInstanceManagementClient: :vartype location: azure.mgmt.containerinstance.aio.operations.LocationOperations :ivar containers: ContainersOperations operations :vartype containers: azure.mgmt.containerinstance.aio.operations.ContainersOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar subnet_service_association_link: SubnetServiceAssociationLinkOperations operations + :vartype subnet_service_association_link: + azure.mgmt.containerinstance.aio.operations.SubnetServiceAssociationLinkOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: Subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :param base_url: Service URL. Default value is 'https://management.azure.com'. + :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ @@ -51,24 +64,26 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = ContainerInstanceManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = ContainerInstanceManagementClientConfiguration( + 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._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.container_groups = ContainerGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.container_groups = ContainerGroupsOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.location = LocationOperations(self._client, self._config, self._serialize, self._deserialize) self.containers = ContainersOperations(self._client, self._config, self._serialize, self._deserialize) + self.subnet_service_association_link = SubnetServiceAssociationLinkOperations( + self._client, self._config, self._serialize, self._deserialize + ) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -77,7 +92,7 @@ def _send_request( >>> response = await client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + 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 diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_patch.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_patch.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/__init__.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/__init__.py index 65bb6fbdb75f..dcde5cd3ada4 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/__init__.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/__init__.py @@ -10,10 +10,18 @@ from ._operations import Operations from ._location_operations import LocationOperations from ._containers_operations import ContainersOperations +from ._subnet_service_association_link_operations import SubnetServiceAssociationLinkOperations + +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__ = [ - 'ContainerGroupsOperations', - 'Operations', - 'LocationOperations', - 'ContainersOperations', + "ContainerGroupsOperations", + "Operations", + "LocationOperations", + "ContainersOperations", + "SubnetServiceAssociationLinkOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_container_groups_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_container_groups_operations.py index b5a227ca2596..251c3e33d7b9 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_container_groups_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_container_groups_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,54 +6,67 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, List, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse 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, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator 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 azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._container_groups_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_outbound_network_dependencies_endpoints_request, build_get_request, build_list_by_resource_group_request, build_list_request, build_restart_request_initial, build_start_request_initial, build_stop_request, build_update_request -T = TypeVar('T') +from ...operations._container_groups_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_outbound_network_dependencies_endpoints_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_restart_request, + build_start_request, + build_stop_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ContainerGroupsOperations: - """ContainerGroupsOperations 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 ContainerGroupsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.containerinstance.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.containerinstance.aio.ContainerInstanceManagementClient`'s + :attr:`container_groups` 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, - **kwargs: Any - ) -> AsyncIterable["_models.ContainerGroupListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.ContainerGroup"]: """Get a list of container groups in the specified subscription. Get a list of container groups in the specified subscription. This operation returns properties @@ -60,35 +74,41 @@ def list( address type, OS type, state, and volumes. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ContainerGroupListResult or the result of - cls(response) + :return: An iterator like instance of either ContainerGroup or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.ContainerGroupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroupListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroupListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + 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, - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -102,7 +122,9 @@ 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]: @@ -111,58 +133,59 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups"} # type: ignore @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.ContainerGroupListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ContainerGroup"]: """Get a list of container groups in the specified subscription and resource group. Get a list of container groups in a specified subscription and resource group. This operation returns properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes. - :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 ContainerGroupListResult or the result of - cls(response) + :return: An iterator like instance of either ContainerGroup or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.ContainerGroupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroupListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroupListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -176,7 +199,9 @@ 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]: @@ -185,96 +210,111 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> "_models.ContainerGroup": + async def get(self, resource_group_name: str, container_group_name: str, **kwargs: Any) -> _models.ContainerGroup: """Get the properties of the specified container group. Gets the properties of the specified container group in the specified subscription and resource group. The operation returns the properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ContainerGroup, or the result of cls(response) + :return: ContainerGroup or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self.get.metadata['url'], + 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) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, container_group_name: str, - container_group: "_models.ContainerGroup", + container_group: Union[_models.ContainerGroup, IO], **kwargs: Any - ) -> "_models.ContainerGroup": - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(container_group, 'ContainerGroup') + ) -> _models.ContainerGroup: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(container_group, (IO, bytes)): + _content = container_group + else: + _json = self._serialize.body(container_group, "ContainerGroup") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, container_group_name=container_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -282,37 +322,42 @@ async def _create_or_update_initial( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, container_group_name: str, - container_group: "_models.ContainerGroup", + container_group: _models.ContainerGroup, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.ContainerGroup"]: + ) -> AsyncLROPoller[_models.ContainerGroup]: """Create or update container groups. Create or update container groups with specified configurations. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :param container_group: The properties of the container group to be created or updated. + Required. :type container_group: ~azure.mgmt.containerinstance.models.ContainerGroup + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -324,134 +369,289 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either ContainerGroup or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + container_group_name: str, + container_group: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ContainerGroup]: + """Create or update container groups. + + Create or update container groups with specified configurations. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_group: The properties of the container group to be created or updated. + Required. + :type container_group: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ContainerGroup or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + container_group_name: str, + container_group: Union[_models.ContainerGroup, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ContainerGroup]: + """Create or update container groups. + + Create or update container groups with specified configurations. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_group: The properties of the container group to be created or updated. Is + either a model type or a IO type. Required. + :type container_group: ~azure.mgmt.containerinstance.models.ContainerGroup or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ContainerGroup or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_initial( + raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, container_group=container_group, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore - @distributed_trace_async + @overload async def update( self, resource_group_name: str, container_group_name: str, - resource: "_models.Resource", + resource: _models.Resource, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ContainerGroup": + ) -> _models.ContainerGroup: """Update container groups. Updates container group tags with specified values. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param resource: The container group resource with just the tags to be updated. + :param resource: The container group resource with just the tags to be updated. Required. :type resource: ~azure.mgmt.containerinstance.models.Resource + :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: ContainerGroup or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + container_group_name: str, + resource: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ContainerGroup: + """Update container groups. + + Updates container group tags with specified values. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param resource: The container group resource with just the tags to be updated. Required. + :type resource: 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: ContainerGroup, or the result of cls(response) + :return: ContainerGroup or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @distributed_trace_async + async def update( + self, resource_group_name: str, container_group_name: str, resource: Union[_models.Resource, IO], **kwargs: Any + ) -> _models.ContainerGroup: + """Update container groups. - _json = self._serialize.body(resource, 'Resource') + Updates container group tags with specified values. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param resource: The container group resource with just the tags to be updated. Is either a + model type or a IO type. Required. + :type resource: ~azure.mgmt.containerinstance.models.Resource 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: ContainerGroup or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IO, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "Resource") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore async def _delete_initial( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> Optional["_models.ContainerGroup"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ContainerGroup"]] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + self, resource_group_name: str, container_group_name: str, **kwargs: Any + ) -> Optional[_models.ContainerGroup]: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ContainerGroup]] + + request = build_delete_request( resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -460,31 +660,27 @@ async def _delete_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.ContainerGroup"]: + self, resource_group_name: str, container_group_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.ContainerGroup]: """Delete the specified container group. Delete the specified container group in the specified subscription and resource group. The operation does not delete other resources provided by the user, such as volumes. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -497,70 +693,79 @@ async def begin_delete( :return: An instance of AsyncLROPoller that returns either ContainerGroup or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore - async def _restart_initial( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + async def _restart_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_restart_request( resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self._restart_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._restart_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: @@ -570,24 +775,20 @@ async def _restart_initial( if cls: return cls(pipeline_response, None, {}) - _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart'} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart"} # type: ignore @distributed_trace_async async def begin_restart( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Restarts all containers in a container group. Restarts all containers in a container group in place. If container image has updates, new image will be downloaded. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -599,82 +800,92 @@ async def begin_restart( Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._restart_initial( + raw_result = await self._restart_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart'} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart"} # type: ignore @distributed_trace_async - async def stop( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + async def stop( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: """Stops all containers in a container group. Stops all containers in a container group. Compute resources will be deallocated and billing will stop. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_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', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_stop_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self.stop.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: @@ -684,59 +895,59 @@ async def stop( if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/stop"} # type: ignore - - async def _start_initial( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + async def _start_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_start_request( resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self._start_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._start_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response - if response.status_code not in [202]: + if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start'} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start"} # type: ignore @distributed_trace_async async def begin_start( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Starts all containers in a container group. Starts all containers in a container group. Compute resources will be allocated and billing will start. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -748,94 +959,103 @@ async def begin_start( Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._start_initial( + raw_result = await self._start_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start'} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start"} # type: ignore @distributed_trace_async async def get_outbound_network_dependencies_endpoints( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> List[str]: """Get all network dependencies for container group. Gets all the network dependencies for this container group to allow complete control of network setting and configuration. For container groups, this will always be an empty list. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: list of str, or the result of cls(response) + :return: list of str or the result of cls(response) :rtype: list[str] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[List[str]] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[List[str]] - request = build_get_outbound_network_dependencies_endpoints_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self.get_outbound_network_dependencies_endpoints.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_outbound_network_dependencies_endpoints.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('[str]', pipeline_response) + deserialized = self._deserialize("[str]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_outbound_network_dependencies_endpoints.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/outboundNetworkDependenciesEndpoints'} # type: ignore - + get_outbound_network_dependencies_endpoints.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/outboundNetworkDependenciesEndpoints"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_containers_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_containers_operations.py index b2c891faa5ec..3b457fa377a5 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_containers_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_containers_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,44 +6,52 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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.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._containers_operations import build_attach_request, build_execute_command_request, build_list_logs_request -T = TypeVar('T') +from ...operations._containers_operations import ( + build_attach_request, + build_execute_command_request, + build_list_logs_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ContainersOperations: - """ContainersOperations 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 ContainersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.containerinstance.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.containerinstance.aio.ContainerInstanceManagementClient`'s + :attr:`containers` 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_async async def list_logs( @@ -53,64 +62,137 @@ async def list_logs( tail: Optional[int] = None, timestamps: Optional[bool] = None, **kwargs: Any - ) -> "_models.Logs": + ) -> _models.Logs: """Get the logs for a specified container instance. Get the logs for a specified container instance in a specified resource group and container 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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param container_name: The name of the container instance. + :param container_name: The name of the container instance. Required. :type container_name: str :param tail: The number of lines to show from the tail of the container instance log. If not - provided, all available logs are shown up to 4mb. + provided, all available logs are shown up to 4mb. Default value is None. :type tail: int :param timestamps: If true, adds a timestamp at the beginning of every line of log output. If - not provided, defaults to false. + not provided, defaults to false. Default value is None. :type timestamps: bool :keyword callable cls: A custom type or function that will be passed the direct response - :return: Logs, or the result of cls(response) + :return: Logs or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.Logs - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Logs"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Logs] - request = build_list_logs_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, container_name=container_name, + subscription_id=self._config.subscription_id, tail=tail, timestamps=timestamps, - template_url=self.list_logs.metadata['url'], + api_version=api_version, + template_url=self.list_logs.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Logs', pipeline_response) + deserialized = self._deserialize("Logs", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_logs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs'} # type: ignore + list_logs.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs"} # type: ignore + + @overload + async def execute_command( + self, + resource_group_name: str, + container_group_name: str, + container_name: str, + container_exec_request: _models.ContainerExecRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ContainerExecResponse: + """Executes a command in a specific container instance. + + Executes a command for a specific container instance in a specified resource group and + container group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_name: The name of the container instance. Required. + :type container_name: str + :param container_exec_request: The request for the exec command. Required. + :type container_exec_request: ~azure.mgmt.containerinstance.models.ContainerExecRequest + :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: ContainerExecResponse or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerExecResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def execute_command( + self, + resource_group_name: str, + container_group_name: str, + container_name: str, + container_exec_request: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ContainerExecResponse: + """Executes a command in a specific container instance. + + Executes a command for a specific container instance in a specified resource group and + container group. + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_name: The name of the container instance. Required. + :type container_name: str + :param container_exec_request: The request for the exec command. Required. + :type container_exec_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ContainerExecResponse or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerExecResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def execute_command( @@ -118,120 +200,141 @@ async def execute_command( resource_group_name: str, container_group_name: str, container_name: str, - container_exec_request: "_models.ContainerExecRequest", + container_exec_request: Union[_models.ContainerExecRequest, IO], **kwargs: Any - ) -> "_models.ContainerExecResponse": + ) -> _models.ContainerExecResponse: """Executes a command in a specific container instance. Executes a command for a specific container instance in a specified resource group and container 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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param container_name: The name of the container instance. + :param container_name: The name of the container instance. Required. :type container_name: str - :param container_exec_request: The request for the exec command. - :type container_exec_request: ~azure.mgmt.containerinstance.models.ContainerExecRequest + :param container_exec_request: The request for the exec command. Is either a model type or a IO + type. Required. + :type container_exec_request: ~azure.mgmt.containerinstance.models.ContainerExecRequest 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: ContainerExecResponse, or the result of cls(response) + :return: ContainerExecResponse or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerExecResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerExecResponse"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(container_exec_request, 'ContainerExecRequest') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerExecResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(container_exec_request, (IO, bytes)): + _content = container_exec_request + else: + _json = self._serialize.body(container_exec_request, "ContainerExecRequest") request = build_execute_command_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute_command.metadata['url'], + content=_content, + template_url=self.execute_command.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerExecResponse', pipeline_response) + deserialized = self._deserialize("ContainerExecResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute_command.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/exec'} # type: ignore - + execute_command.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/exec"} # type: ignore @distributed_trace_async async def attach( - self, - resource_group_name: str, - container_group_name: str, - container_name: str, - **kwargs: Any - ) -> "_models.ContainerAttachResponse": + self, resource_group_name: str, container_group_name: str, container_name: str, **kwargs: Any + ) -> _models.ContainerAttachResponse: """Attach to the output of a specific container instance. Attach to the output stream of a specific container instance in a specified resource group and container 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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param container_name: The name of the container instance. + :param container_name: The name of the container instance. Required. :type container_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ContainerAttachResponse, or the result of cls(response) + :return: ContainerAttachResponse or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerAttachResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerAttachResponse"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerAttachResponse] - request = build_attach_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, container_name=container_name, - template_url=self.attach.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.attach.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerAttachResponse', pipeline_response) + deserialized = self._deserialize("ContainerAttachResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - attach.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/attach'} # type: ignore - + attach.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/attach"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_location_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_location_operations.py index 00dcf1673d3f..ff1dbf82398b 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_location_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_location_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,88 +6,97 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse 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, + 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._location_operations import build_list_cached_images_request, build_list_capabilities_request, build_list_usage_request -T = TypeVar('T') +from ...operations._location_operations import ( + build_list_cached_images_request, + build_list_capabilities_request, + build_list_usage_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class LocationOperations: - """LocationOperations 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 LocationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.containerinstance.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.containerinstance.aio.ContainerInstanceManagementClient`'s + :attr:`location` 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_usage( - self, - location: str, - **kwargs: Any - ) -> AsyncIterable["_models.UsageListResult"]: + def list_usage(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Usage"]: """Get the usage for a subscription. - :param location: The identifier for the physical azure location. + :param location: The identifier for the physical azure location. Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either UsageListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.UsageListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.UsageListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.UsageListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_usage_request( - subscription_id=self._config.subscription_id, location=location, - template_url=self.list_usage.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_usage.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_usage_request( - subscription_id=self._config.subscription_id, - location=location, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -100,7 +110,9 @@ 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]: @@ -109,56 +121,55 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_usage.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/usages'} # type: ignore + list_usage.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/usages"} # type: ignore @distributed_trace - def list_cached_images( - self, - location: str, - **kwargs: Any - ) -> AsyncIterable["_models.CachedImagesListResult"]: + def list_cached_images(self, location: str, **kwargs: Any) -> AsyncIterable["_models.CachedImages"]: """Get the list of cached images. Get the list of cached images on specific OS type for a subscription in a region. - :param location: The identifier for the physical azure location. + :param location: The identifier for the physical azure location. Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CachedImagesListResult or the result of - cls(response) + :return: An iterator like instance of either CachedImages or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.CachedImagesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.CachedImages] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CachedImagesListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CachedImagesListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_cached_images_request( - subscription_id=self._config.subscription_id, location=location, - template_url=self.list_cached_images.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_cached_images.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_cached_images_request( - subscription_id=self._config.subscription_id, - location=location, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -172,7 +183,9 @@ 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]: @@ -181,56 +194,55 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_cached_images.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/cachedImages'} # type: ignore + list_cached_images.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/cachedImages"} # type: ignore @distributed_trace - def list_capabilities( - self, - location: str, - **kwargs: Any - ) -> AsyncIterable["_models.CapabilitiesListResult"]: + def list_capabilities(self, location: str, **kwargs: Any) -> AsyncIterable["_models.Capabilities"]: """Get the list of capabilities of the location. Get the list of CPU/memory/GPU capabilities of a region. - :param location: The identifier for the physical azure location. + :param location: The identifier for the physical azure location. Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CapabilitiesListResult or the result of - cls(response) + :return: An iterator like instance of either Capabilities or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.CapabilitiesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.Capabilities] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CapabilitiesListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CapabilitiesListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_capabilities_request( - subscription_id=self._config.subscription_id, location=location, - template_url=self.list_capabilities.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_capabilities.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_capabilities_request( - subscription_id=self._config.subscription_id, - location=location, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -244,7 +256,9 @@ 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]: @@ -253,8 +267,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_capabilities.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/capabilities'} # type: ignore + list_capabilities.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/capabilities"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_operations.py index 56c26b2924ba..fbc8d66a7c46 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,81 +6,89 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse 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, + 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._operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.containerinstance.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.containerinstance.aio.ContainerInstanceManagementClient`'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") @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """List the operations for Azure Container Instance service. :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.containerinstance.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.containerinstance.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -93,7 +102,9 @@ 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]: @@ -102,8 +113,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.ContainerInstance/operations'} # type: ignore + list.metadata = {"url": "/providers/Microsoft.ContainerInstance/operations"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_patch.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/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/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_subnet_service_association_link_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_subnet_service_association_link_operations.py new file mode 100644 index 000000000000..895b0d81f031 --- /dev/null +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_subnet_service_association_link_operations.py @@ -0,0 +1,161 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._subnet_service_association_link_operations import build_delete_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class SubnetServiceAssociationLinkOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.containerinstance.aio.ContainerInstanceManagementClient`'s + :attr:`subnet_service_association_link` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, virtual_network_name: str, subnet_name: str, **kwargs: Any + ) -> None: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + virtual_network_name=virtual_network_name, + subnet_name=subnet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/providers/Microsoft.ContainerInstance/serviceAssociationLinks/default"} # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, virtual_network_name: str, subnet_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Delete container group virtual network association links. + + Delete container group virtual network association links. The operation does not delete other + resources provided by the user. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param virtual_network_name: The name of the virtual network. Required. + :type virtual_network_name: str + :param subnet_name: The name of the subnet. Required. + :type subnet_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + virtual_network_name=virtual_network_name, + subnet_name=subnet_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/providers/Microsoft.ContainerInstance/serviceAssociationLinks/default"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/__init__.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/__init__.py index e8bda58e56f0..dfafea4ddb9a 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/__init__.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/__init__.py @@ -13,7 +13,6 @@ from ._models_py3 import CapabilitiesCapabilities from ._models_py3 import CapabilitiesListResult from ._models_py3 import CloudErrorBody -from ._models_py3 import Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties from ._models_py3 import Container from ._models_py3 import ContainerAttachResponse from ._models_py3 import ContainerExec @@ -24,6 +23,7 @@ from ._models_py3 import ContainerGroupDiagnostics from ._models_py3 import ContainerGroupIdentity from ._models_py3 import ContainerGroupListResult +from ._models_py3 import ContainerGroupProperties from ._models_py3 import ContainerGroupPropertiesInstanceView from ._models_py3 import ContainerGroupSubnetId from ._models_py3 import ContainerHttpGet @@ -55,87 +55,91 @@ from ._models_py3 import Usage from ._models_py3 import UsageListResult from ._models_py3 import UsageName +from ._models_py3 import UserAssignedIdentities from ._models_py3 import Volume from ._models_py3 import VolumeMount - -from ._container_instance_management_client_enums import ( - AutoGeneratedDomainNameLabelScope, - ContainerGroupIpAddressType, - ContainerGroupNetworkProtocol, - ContainerGroupRestartPolicy, - ContainerGroupSku, - ContainerInstanceOperationsOrigin, - ContainerNetworkProtocol, - GpuSku, - LogAnalyticsLogType, - OperatingSystemTypes, - ResourceIdentityType, - Scheme, -) +from ._container_instance_management_client_enums import ContainerGroupIpAddressType +from ._container_instance_management_client_enums import ContainerGroupNetworkProtocol +from ._container_instance_management_client_enums import ContainerGroupRestartPolicy +from ._container_instance_management_client_enums import ContainerGroupSku +from ._container_instance_management_client_enums import ContainerInstanceOperationsOrigin +from ._container_instance_management_client_enums import ContainerNetworkProtocol +from ._container_instance_management_client_enums import DnsNameLabelReusePolicy +from ._container_instance_management_client_enums import GpuSku +from ._container_instance_management_client_enums import LogAnalyticsLogType +from ._container_instance_management_client_enums import OperatingSystemTypes +from ._container_instance_management_client_enums import ResourceIdentityType +from ._container_instance_management_client_enums import Scheme +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__ = [ - 'AzureFileVolume', - 'CachedImages', - 'CachedImagesListResult', - 'Capabilities', - 'CapabilitiesCapabilities', - 'CapabilitiesListResult', - 'CloudErrorBody', - 'Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties', - 'Container', - 'ContainerAttachResponse', - 'ContainerExec', - 'ContainerExecRequest', - 'ContainerExecRequestTerminalSize', - 'ContainerExecResponse', - 'ContainerGroup', - 'ContainerGroupDiagnostics', - 'ContainerGroupIdentity', - 'ContainerGroupListResult', - 'ContainerGroupPropertiesInstanceView', - 'ContainerGroupSubnetId', - 'ContainerHttpGet', - 'ContainerPort', - 'ContainerProbe', - 'ContainerPropertiesInstanceView', - 'ContainerState', - 'DnsConfiguration', - 'EncryptionProperties', - 'EnvironmentVariable', - 'Event', - 'GitRepoVolume', - 'GpuResource', - 'HttpHeader', - 'ImageRegistryCredential', - 'InitContainerDefinition', - 'InitContainerPropertiesDefinitionInstanceView', - 'IpAddress', - 'LogAnalytics', - 'Logs', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'Port', - 'Resource', - 'ResourceLimits', - 'ResourceRequests', - 'ResourceRequirements', - 'Usage', - 'UsageListResult', - 'UsageName', - 'Volume', - 'VolumeMount', - 'AutoGeneratedDomainNameLabelScope', - 'ContainerGroupIpAddressType', - 'ContainerGroupNetworkProtocol', - 'ContainerGroupRestartPolicy', - 'ContainerGroupSku', - 'ContainerInstanceOperationsOrigin', - 'ContainerNetworkProtocol', - 'GpuSku', - 'LogAnalyticsLogType', - 'OperatingSystemTypes', - 'ResourceIdentityType', - 'Scheme', + "AzureFileVolume", + "CachedImages", + "CachedImagesListResult", + "Capabilities", + "CapabilitiesCapabilities", + "CapabilitiesListResult", + "CloudErrorBody", + "Container", + "ContainerAttachResponse", + "ContainerExec", + "ContainerExecRequest", + "ContainerExecRequestTerminalSize", + "ContainerExecResponse", + "ContainerGroup", + "ContainerGroupDiagnostics", + "ContainerGroupIdentity", + "ContainerGroupListResult", + "ContainerGroupProperties", + "ContainerGroupPropertiesInstanceView", + "ContainerGroupSubnetId", + "ContainerHttpGet", + "ContainerPort", + "ContainerProbe", + "ContainerPropertiesInstanceView", + "ContainerState", + "DnsConfiguration", + "EncryptionProperties", + "EnvironmentVariable", + "Event", + "GitRepoVolume", + "GpuResource", + "HttpHeader", + "ImageRegistryCredential", + "InitContainerDefinition", + "InitContainerPropertiesDefinitionInstanceView", + "IpAddress", + "LogAnalytics", + "Logs", + "Operation", + "OperationDisplay", + "OperationListResult", + "Port", + "Resource", + "ResourceLimits", + "ResourceRequests", + "ResourceRequirements", + "Usage", + "UsageListResult", + "UsageName", + "UserAssignedIdentities", + "Volume", + "VolumeMount", + "ContainerGroupIpAddressType", + "ContainerGroupNetworkProtocol", + "ContainerGroupRestartPolicy", + "ContainerGroupSku", + "ContainerInstanceOperationsOrigin", + "ContainerNetworkProtocol", + "DnsNameLabelReusePolicy", + "GpuSku", + "LogAnalyticsLogType", + "OperatingSystemTypes", + "ResourceIdentityType", + "Scheme", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_container_instance_management_client_enums.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_container_instance_management_client_enums.py index d41d17c8137b..3dd132e4a9d0 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_container_instance_management_client_enums.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_container_instance_management_client_enums.py @@ -7,91 +7,99 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class AutoGeneratedDomainNameLabelScope(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The value representing the security enum. - """ - - UNSECURE = "Unsecure" - TENANT_REUSE = "TenantReuse" - SUBSCRIPTION_REUSE = "SubscriptionReuse" - RESOURCE_GROUP_REUSE = "ResourceGroupReuse" - NOREUSE = "Noreuse" - -class ContainerGroupIpAddressType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Specifies if the IP is exposed to the public internet or private VNET. - """ +class ContainerGroupIpAddressType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies if the IP is exposed to the public internet or private VNET.""" PUBLIC = "Public" PRIVATE = "Private" -class ContainerGroupNetworkProtocol(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The protocol associated with the port. - """ + +class ContainerGroupNetworkProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The protocol associated with the port.""" TCP = "TCP" UDP = "UDP" -class ContainerGroupRestartPolicy(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class ContainerGroupRestartPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Restart policy for all containers within the container group. - - + + * ``Always`` Always restart * ``OnFailure`` Restart on failure - * ``Never`` Never restart + * ``Never`` Never restart. """ ALWAYS = "Always" ON_FAILURE = "OnFailure" NEVER = "Never" -class ContainerGroupSku(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The container group SKU. - """ + +class ContainerGroupSku(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The container group SKU.""" STANDARD = "Standard" DEDICATED = "Dedicated" -class ContainerInstanceOperationsOrigin(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The intended executor of the operation. - """ + +class ContainerInstanceOperationsOrigin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation.""" USER = "User" SYSTEM = "System" -class ContainerNetworkProtocol(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The protocol associated with the port. - """ + +class ContainerNetworkProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The protocol associated with the port.""" TCP = "TCP" UDP = "UDP" -class GpuSku(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The SKU of the GPU resource. + +class DnsNameLabelReusePolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The value representing the security enum. The 'Unsecure' value is the default value if not + selected and means the object's domain name label is not secured against subdomain takeover. + The 'TenantReuse' value is the default value if selected and means the object's domain name + label can be reused within the same tenant. The 'SubscriptionReuse' value means the object's + domain name label can be reused within the same subscription. The 'ResourceGroupReuse' value + means the object's domain name label can be reused within the same resource group. The + 'NoReuse' value means the object's domain name label cannot be reused within the same resource + group, subscription, or tenant. """ + UNSECURE = "Unsecure" + TENANT_REUSE = "TenantReuse" + SUBSCRIPTION_REUSE = "SubscriptionReuse" + RESOURCE_GROUP_REUSE = "ResourceGroupReuse" + NOREUSE = "Noreuse" + + +class GpuSku(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The SKU of the GPU resource.""" + K80 = "K80" P100 = "P100" V100 = "V100" -class LogAnalyticsLogType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The log type to be used. - """ + +class LogAnalyticsLogType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The log type to be used.""" CONTAINER_INSIGHTS = "ContainerInsights" CONTAINER_INSTANCE_LOGS = "ContainerInstanceLogs" -class OperatingSystemTypes(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The operating system type required by the containers in the container group. - """ + +class OperatingSystemTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operating system type required by the containers in the container group.""" WINDOWS = "Windows" LINUX = "Linux" -class ResourceIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of identity used for the container group. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the container group. @@ -102,9 +110,9 @@ class ResourceIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" NONE = "None" -class Scheme(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The scheme. - """ + +class Scheme(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The scheme.""" HTTP = "http" HTTPS = "https" diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_models_py3.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_models_py3.py index ab7f49cff2af..579bedb651b3 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_models_py3.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/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,40 +7,48 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Dict, List, Optional, Union +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from .. import _serialization -from ._container_instance_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class AzureFileVolume(msrest.serialization.Model): +class AzureFileVolume(_serialization.Model): """The properties of the Azure File volume. Azure File shares are mounted as volumes. All required parameters must be populated in order to send to Azure. - :ivar share_name: Required. The name of the Azure File share to be mounted as a volume. + :ivar share_name: The name of the Azure File share to be mounted as a volume. Required. :vartype share_name: str :ivar read_only: The flag indicating whether the Azure File shared mounted as a volume is read-only. :vartype read_only: bool - :ivar storage_account_name: Required. The name of the storage account that contains the Azure - File share. + :ivar storage_account_name: The name of the storage account that contains the Azure File share. + Required. :vartype storage_account_name: str :ivar storage_account_key: The storage account access key used to access the Azure File share. :vartype storage_account_key: str """ _validation = { - 'share_name': {'required': True}, - 'storage_account_name': {'required': True}, + "share_name": {"required": True}, + "storage_account_name": {"required": True}, } _attribute_map = { - 'share_name': {'key': 'shareName', 'type': 'str'}, - 'read_only': {'key': 'readOnly', 'type': 'bool'}, - 'storage_account_name': {'key': 'storageAccountName', 'type': 'str'}, - 'storage_account_key': {'key': 'storageAccountKey', 'type': 'str'}, + "share_name": {"key": "shareName", "type": "str"}, + "read_only": {"key": "readOnly", "type": "bool"}, + "storage_account_name": {"key": "storageAccountName", "type": "str"}, + "storage_account_key": {"key": "storageAccountKey", "type": "str"}, } def __init__( @@ -52,65 +61,59 @@ def __init__( **kwargs ): """ - :keyword share_name: Required. The name of the Azure File share to be mounted as a volume. + :keyword share_name: The name of the Azure File share to be mounted as a volume. Required. :paramtype share_name: str :keyword read_only: The flag indicating whether the Azure File shared mounted as a volume is read-only. :paramtype read_only: bool - :keyword storage_account_name: Required. The name of the storage account that contains the - Azure File share. + :keyword storage_account_name: The name of the storage account that contains the Azure File + share. Required. :paramtype storage_account_name: str :keyword storage_account_key: The storage account access key used to access the Azure File share. :paramtype storage_account_key: str """ - super(AzureFileVolume, self).__init__(**kwargs) + super().__init__(**kwargs) self.share_name = share_name self.read_only = read_only self.storage_account_name = storage_account_name self.storage_account_key = storage_account_key -class CachedImages(msrest.serialization.Model): +class CachedImages(_serialization.Model): """The cached image and OS type. All required parameters must be populated in order to send to Azure. - :ivar os_type: Required. The OS type of the cached image. + :ivar os_type: The OS type of the cached image. Required. :vartype os_type: str - :ivar image: Required. The cached image name. + :ivar image: The cached image name. Required. :vartype image: str """ _validation = { - 'os_type': {'required': True}, - 'image': {'required': True}, + "os_type": {"required": True}, + "image": {"required": True}, } _attribute_map = { - 'os_type': {'key': 'osType', 'type': 'str'}, - 'image': {'key': 'image', 'type': 'str'}, + "os_type": {"key": "osType", "type": "str"}, + "image": {"key": "image", "type": "str"}, } - def __init__( - self, - *, - os_type: str, - image: str, - **kwargs - ): + def __init__(self, *, os_type: str, image: str, **kwargs): """ - :keyword os_type: Required. The OS type of the cached image. + :keyword os_type: The OS type of the cached image. Required. :paramtype os_type: str - :keyword image: Required. The cached image name. + :keyword image: The cached image name. Required. :paramtype image: str """ - super(CachedImages, self).__init__(**kwargs) + super().__init__(**kwargs) self.os_type = os_type self.image = image -class CachedImagesListResult(msrest.serialization.Model): +class CachedImagesListResult(_serialization.Model): """The response containing cached images. :ivar value: The list of cached images. @@ -120,16 +123,12 @@ class CachedImagesListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[CachedImages]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[CachedImages]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["CachedImages"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.CachedImages"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of cached images. @@ -137,12 +136,12 @@ def __init__( :keyword next_link: The URI to fetch the next page of cached images. :paramtype next_link: str """ - super(CachedImagesListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class Capabilities(msrest.serialization.Model): +class Capabilities(_serialization.Model): """The regional capabilities. Variables are only populated by the server, and will be ignored when sending a request. @@ -162,30 +161,26 @@ class Capabilities(msrest.serialization.Model): """ _validation = { - 'resource_type': {'readonly': True}, - 'os_type': {'readonly': True}, - 'location': {'readonly': True}, - 'ip_address_type': {'readonly': True}, - 'gpu': {'readonly': True}, - 'capabilities': {'readonly': True}, + "resource_type": {"readonly": True}, + "os_type": {"readonly": True}, + "location": {"readonly": True}, + "ip_address_type": {"readonly": True}, + "gpu": {"readonly": True}, + "capabilities": {"readonly": True}, } _attribute_map = { - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'os_type': {'key': 'osType', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'ip_address_type': {'key': 'ipAddressType', 'type': 'str'}, - 'gpu': {'key': 'gpu', 'type': 'str'}, - 'capabilities': {'key': 'capabilities', 'type': 'CapabilitiesCapabilities'}, + "resource_type": {"key": "resourceType", "type": "str"}, + "os_type": {"key": "osType", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "ip_address_type": {"key": "ipAddressType", "type": "str"}, + "gpu": {"key": "gpu", "type": "str"}, + "capabilities": {"key": "capabilities", "type": "CapabilitiesCapabilities"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Capabilities, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.resource_type = None self.os_type = None self.location = None @@ -194,7 +189,7 @@ def __init__( self.capabilities = None -class CapabilitiesCapabilities(msrest.serialization.Model): +class CapabilitiesCapabilities(_serialization.Model): """The supported capabilities. Variables are only populated by the server, and will be ignored when sending a request. @@ -208,30 +203,26 @@ class CapabilitiesCapabilities(msrest.serialization.Model): """ _validation = { - 'max_memory_in_gb': {'readonly': True}, - 'max_cpu': {'readonly': True}, - 'max_gpu_count': {'readonly': True}, + "max_memory_in_gb": {"readonly": True}, + "max_cpu": {"readonly": True}, + "max_gpu_count": {"readonly": True}, } _attribute_map = { - 'max_memory_in_gb': {'key': 'maxMemoryInGB', 'type': 'float'}, - 'max_cpu': {'key': 'maxCpu', 'type': 'float'}, - 'max_gpu_count': {'key': 'maxGpuCount', 'type': 'float'}, + "max_memory_in_gb": {"key": "maxMemoryInGB", "type": "float"}, + "max_cpu": {"key": "maxCpu", "type": "float"}, + "max_gpu_count": {"key": "maxGpuCount", "type": "float"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(CapabilitiesCapabilities, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.max_memory_in_gb = None self.max_cpu = None self.max_gpu_count = None -class CapabilitiesListResult(msrest.serialization.Model): +class CapabilitiesListResult(_serialization.Model): """The response containing list of capabilities. :ivar value: The list of capabilities. @@ -241,16 +232,12 @@ class CapabilitiesListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Capabilities]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Capabilities]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["Capabilities"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.Capabilities"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of capabilities. @@ -258,12 +245,12 @@ def __init__( :keyword next_link: The URI to fetch the next page of capabilities. :paramtype next_link: str """ - super(CapabilitiesListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class CloudErrorBody(msrest.serialization.Model): +class CloudErrorBody(_serialization.Model): """An error response from the Container Instance service. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed @@ -280,10 +267,10 @@ class CloudErrorBody(msrest.serialization.Model): """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[CloudErrorBody]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[CloudErrorBody]"}, } def __init__( @@ -292,7 +279,7 @@ def __init__( code: Optional[str] = None, message: Optional[str] = None, target: Optional[str] = None, - details: Optional[List["CloudErrorBody"]] = None, + details: Optional[List["_models.CloudErrorBody"]] = None, **kwargs ): """ @@ -308,55 +295,23 @@ def __init__( :keyword details: A list of additional details about the error. :paramtype details: list[~azure.mgmt.containerinstance.models.CloudErrorBody] """ - super(CloudErrorBody, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message self.target = target self.details = details -class Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties(msrest.serialization.Model): - """Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal id of user assigned identity. - :vartype principal_id: str - :ivar client_id: The client id of user assigned identity. - :vartype client_id: str - """ - - _validation = { - 'principal_id': {'readonly': True}, - 'client_id': {'readonly': True}, - } - - _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'client_id': {'key': 'clientId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties, self).__init__(**kwargs) - self.principal_id = None - self.client_id = None - - -class Container(msrest.serialization.Model): +class Container(_serialization.Model): """A container instance. 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: Required. The user-provided name of the container instance. + :ivar name: The user-provided name of the container instance. Required. :vartype name: str - :ivar image: Required. The name of the image used to create the container instance. + :ivar image: The name of the image used to create the container instance. Required. :vartype image: str :ivar command: The commands to execute within the container instance in exec form. :vartype command: list[str] @@ -366,7 +321,7 @@ class Container(msrest.serialization.Model): :vartype environment_variables: list[~azure.mgmt.containerinstance.models.EnvironmentVariable] :ivar instance_view: The instance view of the container instance. Only valid in response. :vartype instance_view: ~azure.mgmt.containerinstance.models.ContainerPropertiesInstanceView - :ivar resources: Required. The resource requirements of the container instance. + :ivar resources: The resource requirements of the container instance. Required. :vartype resources: ~azure.mgmt.containerinstance.models.ResourceRequirements :ivar volume_mounts: The volume mounts available to the container instance. :vartype volume_mounts: list[~azure.mgmt.containerinstance.models.VolumeMount] @@ -377,23 +332,23 @@ class Container(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, - 'image': {'required': True}, - 'instance_view': {'readonly': True}, - 'resources': {'required': True}, + "name": {"required": True}, + "image": {"required": True}, + "instance_view": {"readonly": True}, + "resources": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'image': {'key': 'properties.image', 'type': 'str'}, - 'command': {'key': 'properties.command', 'type': '[str]'}, - 'ports': {'key': 'properties.ports', 'type': '[ContainerPort]'}, - 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, - 'instance_view': {'key': 'properties.instanceView', 'type': 'ContainerPropertiesInstanceView'}, - 'resources': {'key': 'properties.resources', 'type': 'ResourceRequirements'}, - 'volume_mounts': {'key': 'properties.volumeMounts', 'type': '[VolumeMount]'}, - 'liveness_probe': {'key': 'properties.livenessProbe', 'type': 'ContainerProbe'}, - 'readiness_probe': {'key': 'properties.readinessProbe', 'type': 'ContainerProbe'}, + "name": {"key": "name", "type": "str"}, + "image": {"key": "properties.image", "type": "str"}, + "command": {"key": "properties.command", "type": "[str]"}, + "ports": {"key": "properties.ports", "type": "[ContainerPort]"}, + "environment_variables": {"key": "properties.environmentVariables", "type": "[EnvironmentVariable]"}, + "instance_view": {"key": "properties.instanceView", "type": "ContainerPropertiesInstanceView"}, + "resources": {"key": "properties.resources", "type": "ResourceRequirements"}, + "volume_mounts": {"key": "properties.volumeMounts", "type": "[VolumeMount]"}, + "liveness_probe": {"key": "properties.livenessProbe", "type": "ContainerProbe"}, + "readiness_probe": {"key": "properties.readinessProbe", "type": "ContainerProbe"}, } def __init__( @@ -401,19 +356,19 @@ def __init__( *, name: str, image: str, - resources: "ResourceRequirements", + resources: "_models.ResourceRequirements", command: Optional[List[str]] = None, - ports: Optional[List["ContainerPort"]] = None, - environment_variables: Optional[List["EnvironmentVariable"]] = None, - volume_mounts: Optional[List["VolumeMount"]] = None, - liveness_probe: Optional["ContainerProbe"] = None, - readiness_probe: Optional["ContainerProbe"] = None, + ports: Optional[List["_models.ContainerPort"]] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + volume_mounts: Optional[List["_models.VolumeMount"]] = None, + liveness_probe: Optional["_models.ContainerProbe"] = None, + readiness_probe: Optional["_models.ContainerProbe"] = None, **kwargs ): """ - :keyword name: Required. The user-provided name of the container instance. + :keyword name: The user-provided name of the container instance. Required. :paramtype name: str - :keyword image: Required. The name of the image used to create the container instance. + :keyword image: The name of the image used to create the container instance. Required. :paramtype image: str :keyword command: The commands to execute within the container instance in exec form. :paramtype command: list[str] @@ -422,7 +377,7 @@ def __init__( :keyword environment_variables: The environment variables to set in the container instance. :paramtype environment_variables: list[~azure.mgmt.containerinstance.models.EnvironmentVariable] - :keyword resources: Required. The resource requirements of the container instance. + :keyword resources: The resource requirements of the container instance. Required. :paramtype resources: ~azure.mgmt.containerinstance.models.ResourceRequirements :keyword volume_mounts: The volume mounts available to the container instance. :paramtype volume_mounts: list[~azure.mgmt.containerinstance.models.VolumeMount] @@ -431,7 +386,7 @@ def __init__( :keyword readiness_probe: The readiness probe. :paramtype readiness_probe: ~azure.mgmt.containerinstance.models.ContainerProbe """ - super(Container, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.image = image self.command = command @@ -444,7 +399,7 @@ def __init__( self.readiness_probe = readiness_probe -class ContainerAttachResponse(msrest.serialization.Model): +class ContainerAttachResponse(_serialization.Model): """The information for the output stream from container attach. :ivar web_socket_uri: The uri for the output stream from the attach. @@ -455,17 +410,11 @@ class ContainerAttachResponse(msrest.serialization.Model): """ _attribute_map = { - 'web_socket_uri': {'key': 'webSocketUri', 'type': 'str'}, - 'password': {'key': 'password', 'type': 'str'}, + "web_socket_uri": {"key": "webSocketUri", "type": "str"}, + "password": {"key": "password", "type": "str"}, } - def __init__( - self, - *, - web_socket_uri: Optional[str] = None, - password: Optional[str] = None, - **kwargs - ): + def __init__(self, *, web_socket_uri: Optional[str] = None, password: Optional[str] = None, **kwargs): """ :keyword web_socket_uri: The uri for the output stream from the attach. :paramtype web_socket_uri: str @@ -473,12 +422,12 @@ def __init__( header value when connecting to the websocketUri. :paramtype password: str """ - super(ContainerAttachResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.web_socket_uri = web_socket_uri self.password = password -class ContainerExec(msrest.serialization.Model): +class ContainerExec(_serialization.Model): """The container execution command, for liveness or readiness probe. :ivar command: The commands to execute within the container. @@ -486,24 +435,19 @@ class ContainerExec(msrest.serialization.Model): """ _attribute_map = { - 'command': {'key': 'command', 'type': '[str]'}, + "command": {"key": "command", "type": "[str]"}, } - def __init__( - self, - *, - command: Optional[List[str]] = None, - **kwargs - ): + def __init__(self, *, command: Optional[List[str]] = None, **kwargs): """ :keyword command: The commands to execute within the container. :paramtype command: list[str] """ - super(ContainerExec, self).__init__(**kwargs) + super().__init__(**kwargs) self.command = command -class ContainerExecRequest(msrest.serialization.Model): +class ContainerExecRequest(_serialization.Model): """The container exec request. :ivar command: The command to be executed. @@ -513,15 +457,15 @@ class ContainerExecRequest(msrest.serialization.Model): """ _attribute_map = { - 'command': {'key': 'command', 'type': 'str'}, - 'terminal_size': {'key': 'terminalSize', 'type': 'ContainerExecRequestTerminalSize'}, + "command": {"key": "command", "type": "str"}, + "terminal_size": {"key": "terminalSize", "type": "ContainerExecRequestTerminalSize"}, } def __init__( self, *, command: Optional[str] = None, - terminal_size: Optional["ContainerExecRequestTerminalSize"] = None, + terminal_size: Optional["_models.ContainerExecRequestTerminalSize"] = None, **kwargs ): """ @@ -530,12 +474,12 @@ def __init__( :keyword terminal_size: The size of the terminal. :paramtype terminal_size: ~azure.mgmt.containerinstance.models.ContainerExecRequestTerminalSize """ - super(ContainerExecRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.command = command self.terminal_size = terminal_size -class ContainerExecRequestTerminalSize(msrest.serialization.Model): +class ContainerExecRequestTerminalSize(_serialization.Model): """The size of the terminal. :ivar rows: The row size of the terminal. @@ -545,29 +489,23 @@ class ContainerExecRequestTerminalSize(msrest.serialization.Model): """ _attribute_map = { - 'rows': {'key': 'rows', 'type': 'int'}, - 'cols': {'key': 'cols', 'type': 'int'}, + "rows": {"key": "rows", "type": "int"}, + "cols": {"key": "cols", "type": "int"}, } - def __init__( - self, - *, - rows: Optional[int] = None, - cols: Optional[int] = None, - **kwargs - ): + def __init__(self, *, rows: Optional[int] = None, cols: Optional[int] = None, **kwargs): """ :keyword rows: The row size of the terminal. :paramtype rows: int :keyword cols: The column size of the terminal. :paramtype cols: int """ - super(ContainerExecRequestTerminalSize, self).__init__(**kwargs) + super().__init__(**kwargs) self.rows = rows self.cols = cols -class ContainerExecResponse(msrest.serialization.Model): +class ContainerExecResponse(_serialization.Model): """The information for the container exec command. :ivar web_socket_uri: The uri for the exec websocket. @@ -577,29 +515,175 @@ class ContainerExecResponse(msrest.serialization.Model): """ _attribute_map = { - 'web_socket_uri': {'key': 'webSocketUri', 'type': 'str'}, - 'password': {'key': 'password', 'type': 'str'}, + "web_socket_uri": {"key": "webSocketUri", "type": "str"}, + "password": {"key": "password", "type": "str"}, } - def __init__( - self, - *, - web_socket_uri: Optional[str] = None, - password: Optional[str] = None, - **kwargs - ): + def __init__(self, *, web_socket_uri: Optional[str] = None, password: Optional[str] = None, **kwargs): """ :keyword web_socket_uri: The uri for the exec websocket. :paramtype web_socket_uri: str :keyword password: The password to start the exec command. :paramtype password: str """ - super(ContainerExecResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.web_socket_uri = web_socket_uri self.password = password -class Resource(msrest.serialization.Model): +class ContainerGroupProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The container group properties. + + 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 identity: The identity of the container group, if configured. + :vartype identity: ~azure.mgmt.containerinstance.models.ContainerGroupIdentity + :ivar provisioning_state: The provisioning state of the container group. This only appears in + the response. + :vartype provisioning_state: str + :ivar containers: The containers within the container group. Required. + :vartype containers: list[~azure.mgmt.containerinstance.models.Container] + :ivar image_registry_credentials: The image registry credentials by which the container group + is created from. + :vartype image_registry_credentials: + list[~azure.mgmt.containerinstance.models.ImageRegistryCredential] + :ivar restart_policy: Restart policy for all containers within the container group. + + + * ``Always`` Always restart + * ``OnFailure`` Restart on failure + * ``Never`` Never restart. Known values are: "Always", "OnFailure", and "Never". + :vartype restart_policy: str or + ~azure.mgmt.containerinstance.models.ContainerGroupRestartPolicy + :ivar ip_address: The IP address type of the container group. + :vartype ip_address: ~azure.mgmt.containerinstance.models.IpAddress + :ivar os_type: The operating system type required by the containers in the container group. + Required. Known values are: "Windows" and "Linux". + :vartype os_type: str or ~azure.mgmt.containerinstance.models.OperatingSystemTypes + :ivar volumes: The list of volumes that can be mounted by containers in this container group. + :vartype volumes: list[~azure.mgmt.containerinstance.models.Volume] + :ivar instance_view: The instance view of the container group. Only valid in response. + :vartype instance_view: + ~azure.mgmt.containerinstance.models.ContainerGroupPropertiesInstanceView + :ivar diagnostics: The diagnostic information for a container group. + :vartype diagnostics: ~azure.mgmt.containerinstance.models.ContainerGroupDiagnostics + :ivar subnet_ids: The subnet resource IDs for a container group. + :vartype subnet_ids: list[~azure.mgmt.containerinstance.models.ContainerGroupSubnetId] + :ivar dns_config: The DNS config information for a container group. + :vartype dns_config: ~azure.mgmt.containerinstance.models.DnsConfiguration + :ivar sku: The SKU for a container group. Known values are: "Standard" and "Dedicated". + :vartype sku: str or ~azure.mgmt.containerinstance.models.ContainerGroupSku + :ivar encryption_properties: The encryption properties for a container group. + :vartype encryption_properties: ~azure.mgmt.containerinstance.models.EncryptionProperties + :ivar init_containers: The init containers for a container group. + :vartype init_containers: list[~azure.mgmt.containerinstance.models.InitContainerDefinition] + """ + + _validation = { + "provisioning_state": {"readonly": True}, + "containers": {"required": True}, + "os_type": {"required": True}, + "instance_view": {"readonly": True}, + } + + _attribute_map = { + "identity": {"key": "identity", "type": "ContainerGroupIdentity"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "containers": {"key": "properties.containers", "type": "[Container]"}, + "image_registry_credentials": { + "key": "properties.imageRegistryCredentials", + "type": "[ImageRegistryCredential]", + }, + "restart_policy": {"key": "properties.restartPolicy", "type": "str"}, + "ip_address": {"key": "properties.ipAddress", "type": "IpAddress"}, + "os_type": {"key": "properties.osType", "type": "str"}, + "volumes": {"key": "properties.volumes", "type": "[Volume]"}, + "instance_view": {"key": "properties.instanceView", "type": "ContainerGroupPropertiesInstanceView"}, + "diagnostics": {"key": "properties.diagnostics", "type": "ContainerGroupDiagnostics"}, + "subnet_ids": {"key": "properties.subnetIds", "type": "[ContainerGroupSubnetId]"}, + "dns_config": {"key": "properties.dnsConfig", "type": "DnsConfiguration"}, + "sku": {"key": "properties.sku", "type": "str"}, + "encryption_properties": {"key": "properties.encryptionProperties", "type": "EncryptionProperties"}, + "init_containers": {"key": "properties.initContainers", "type": "[InitContainerDefinition]"}, + } + + def __init__( + self, + *, + containers: List["_models.Container"], + os_type: Union[str, "_models.OperatingSystemTypes"], + identity: Optional["_models.ContainerGroupIdentity"] = None, + image_registry_credentials: Optional[List["_models.ImageRegistryCredential"]] = None, + restart_policy: Optional[Union[str, "_models.ContainerGroupRestartPolicy"]] = None, + ip_address: Optional["_models.IpAddress"] = None, + volumes: Optional[List["_models.Volume"]] = None, + diagnostics: Optional["_models.ContainerGroupDiagnostics"] = None, + subnet_ids: Optional[List["_models.ContainerGroupSubnetId"]] = None, + dns_config: Optional["_models.DnsConfiguration"] = None, + sku: Optional[Union[str, "_models.ContainerGroupSku"]] = None, + encryption_properties: Optional["_models.EncryptionProperties"] = None, + init_containers: Optional[List["_models.InitContainerDefinition"]] = None, + **kwargs + ): + """ + :keyword identity: The identity of the container group, if configured. + :paramtype identity: ~azure.mgmt.containerinstance.models.ContainerGroupIdentity + :keyword containers: The containers within the container group. Required. + :paramtype containers: list[~azure.mgmt.containerinstance.models.Container] + :keyword image_registry_credentials: The image registry credentials by which the container + group is created from. + :paramtype image_registry_credentials: + list[~azure.mgmt.containerinstance.models.ImageRegistryCredential] + :keyword restart_policy: Restart policy for all containers within the container group. + + + * ``Always`` Always restart + * ``OnFailure`` Restart on failure + * ``Never`` Never restart. Known values are: "Always", "OnFailure", and "Never". + :paramtype restart_policy: str or + ~azure.mgmt.containerinstance.models.ContainerGroupRestartPolicy + :keyword ip_address: The IP address type of the container group. + :paramtype ip_address: ~azure.mgmt.containerinstance.models.IpAddress + :keyword os_type: The operating system type required by the containers in the container group. + Required. Known values are: "Windows" and "Linux". + :paramtype os_type: str or ~azure.mgmt.containerinstance.models.OperatingSystemTypes + :keyword volumes: The list of volumes that can be mounted by containers in this container + group. + :paramtype volumes: list[~azure.mgmt.containerinstance.models.Volume] + :keyword diagnostics: The diagnostic information for a container group. + :paramtype diagnostics: ~azure.mgmt.containerinstance.models.ContainerGroupDiagnostics + :keyword subnet_ids: The subnet resource IDs for a container group. + :paramtype subnet_ids: list[~azure.mgmt.containerinstance.models.ContainerGroupSubnetId] + :keyword dns_config: The DNS config information for a container group. + :paramtype dns_config: ~azure.mgmt.containerinstance.models.DnsConfiguration + :keyword sku: The SKU for a container group. Known values are: "Standard" and "Dedicated". + :paramtype sku: str or ~azure.mgmt.containerinstance.models.ContainerGroupSku + :keyword encryption_properties: The encryption properties for a container group. + :paramtype encryption_properties: ~azure.mgmt.containerinstance.models.EncryptionProperties + :keyword init_containers: The init containers for a container group. + :paramtype init_containers: list[~azure.mgmt.containerinstance.models.InitContainerDefinition] + """ + super().__init__(**kwargs) + self.identity = identity + self.provisioning_state = None + self.containers = containers + self.image_registry_credentials = image_registry_credentials + self.restart_policy = restart_policy + self.ip_address = ip_address + self.os_type = os_type + self.volumes = volumes + self.instance_view = None + self.diagnostics = diagnostics + self.subnet_ids = subnet_ids + self.dns_config = dns_config + self.sku = sku + self.encryption_properties = encryption_properties + self.init_containers = init_containers + + +class Resource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -612,25 +696,25 @@ class Resource(msrest.serialization.Model): :vartype type: str :ivar location: The resource location. :vartype location: str - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] :ivar zones: The zones for the container group. :vartype zones: list[str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'zones': {'key': 'zones', 'type': '[str]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "zones": {"key": "zones", "type": "[str]"}, } def __init__( @@ -644,12 +728,12 @@ def __init__( """ :keyword location: The resource location. :paramtype location: str - :keyword tags: A set of tags. The resource tags. + :keyword tags: The resource tags. :paramtype tags: dict[str, str] :keyword zones: The zones for the container group. :paramtype zones: list[str] """ - super(Resource, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -658,48 +742,36 @@ def __init__( self.zones = zones -class ContainerGroup(Resource): +class ContainerGroup(Resource, ContainerGroupProperties): # pylint: disable=too-many-instance-attributes """A container group. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar id: The resource id. - :vartype id: str - :ivar name: The resource name. - :vartype name: str - :ivar type: The resource type. - :vartype type: str - :ivar location: The resource location. - :vartype location: str - :ivar tags: A set of tags. The resource tags. - :vartype tags: dict[str, str] - :ivar zones: The zones for the container group. - :vartype zones: list[str] :ivar identity: The identity of the container group, if configured. :vartype identity: ~azure.mgmt.containerinstance.models.ContainerGroupIdentity :ivar provisioning_state: The provisioning state of the container group. This only appears in the response. :vartype provisioning_state: str - :ivar containers: Required. The containers within the container group. + :ivar containers: The containers within the container group. Required. :vartype containers: list[~azure.mgmt.containerinstance.models.Container] :ivar image_registry_credentials: The image registry credentials by which the container group is created from. :vartype image_registry_credentials: list[~azure.mgmt.containerinstance.models.ImageRegistryCredential] :ivar restart_policy: Restart policy for all containers within the container group. - - + + * ``Always`` Always restart * ``OnFailure`` Restart on failure - * ``Never`` Never restart. Possible values include: "Always", "OnFailure", "Never". + * ``Never`` Never restart. Known values are: "Always", "OnFailure", and "Never". :vartype restart_policy: str or ~azure.mgmt.containerinstance.models.ContainerGroupRestartPolicy :ivar ip_address: The IP address type of the container group. :vartype ip_address: ~azure.mgmt.containerinstance.models.IpAddress - :ivar os_type: Required. The operating system type required by the containers in the container - group. Possible values include: "Windows", "Linux". + :ivar os_type: The operating system type required by the containers in the container group. + Required. Known values are: "Windows" and "Linux". :vartype os_type: str or ~azure.mgmt.containerinstance.models.OperatingSystemTypes :ivar volumes: The list of volumes that can be mounted by containers in this container group. :vartype volumes: list[~azure.mgmt.containerinstance.models.Volume] @@ -712,96 +784,105 @@ class ContainerGroup(Resource): :vartype subnet_ids: list[~azure.mgmt.containerinstance.models.ContainerGroupSubnetId] :ivar dns_config: The DNS config information for a container group. :vartype dns_config: ~azure.mgmt.containerinstance.models.DnsConfiguration - :ivar sku: The SKU for a container group. Possible values include: "Standard", "Dedicated". + :ivar sku: The SKU for a container group. Known values are: "Standard" and "Dedicated". :vartype sku: str or ~azure.mgmt.containerinstance.models.ContainerGroupSku :ivar encryption_properties: The encryption properties for a container group. :vartype encryption_properties: ~azure.mgmt.containerinstance.models.EncryptionProperties :ivar init_containers: The init containers for a container group. :vartype init_containers: list[~azure.mgmt.containerinstance.models.InitContainerDefinition] + :ivar id: The resource id. + :vartype id: str + :ivar name: The resource name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar location: The resource location. + :vartype location: str + :ivar tags: The resource tags. + :vartype tags: dict[str, str] + :ivar zones: The zones for the container group. + :vartype zones: list[str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'containers': {'required': True}, - 'os_type': {'required': True}, - 'instance_view': {'readonly': True}, + "provisioning_state": {"readonly": True}, + "containers": {"required": True}, + "os_type": {"required": True}, + "instance_view": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'zones': {'key': 'zones', 'type': '[str]'}, - 'identity': {'key': 'identity', 'type': 'ContainerGroupIdentity'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'containers': {'key': 'properties.containers', 'type': '[Container]'}, - 'image_registry_credentials': {'key': 'properties.imageRegistryCredentials', 'type': '[ImageRegistryCredential]'}, - 'restart_policy': {'key': 'properties.restartPolicy', 'type': 'str'}, - 'ip_address': {'key': 'properties.ipAddress', 'type': 'IpAddress'}, - 'os_type': {'key': 'properties.osType', 'type': 'str'}, - 'volumes': {'key': 'properties.volumes', 'type': '[Volume]'}, - 'instance_view': {'key': 'properties.instanceView', 'type': 'ContainerGroupPropertiesInstanceView'}, - 'diagnostics': {'key': 'properties.diagnostics', 'type': 'ContainerGroupDiagnostics'}, - 'subnet_ids': {'key': 'properties.subnetIds', 'type': '[ContainerGroupSubnetId]'}, - 'dns_config': {'key': 'properties.dnsConfig', 'type': 'DnsConfiguration'}, - 'sku': {'key': 'properties.sku', 'type': 'str'}, - 'encryption_properties': {'key': 'properties.encryptionProperties', 'type': 'EncryptionProperties'}, - 'init_containers': {'key': 'properties.initContainers', 'type': '[InitContainerDefinition]'}, + "identity": {"key": "identity", "type": "ContainerGroupIdentity"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "containers": {"key": "properties.containers", "type": "[Container]"}, + "image_registry_credentials": { + "key": "properties.imageRegistryCredentials", + "type": "[ImageRegistryCredential]", + }, + "restart_policy": {"key": "properties.restartPolicy", "type": "str"}, + "ip_address": {"key": "properties.ipAddress", "type": "IpAddress"}, + "os_type": {"key": "properties.osType", "type": "str"}, + "volumes": {"key": "properties.volumes", "type": "[Volume]"}, + "instance_view": {"key": "properties.instanceView", "type": "ContainerGroupPropertiesInstanceView"}, + "diagnostics": {"key": "properties.diagnostics", "type": "ContainerGroupDiagnostics"}, + "subnet_ids": {"key": "properties.subnetIds", "type": "[ContainerGroupSubnetId]"}, + "dns_config": {"key": "properties.dnsConfig", "type": "DnsConfiguration"}, + "sku": {"key": "properties.sku", "type": "str"}, + "encryption_properties": {"key": "properties.encryptionProperties", "type": "EncryptionProperties"}, + "init_containers": {"key": "properties.initContainers", "type": "[InitContainerDefinition]"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "zones": {"key": "zones", "type": "[str]"}, } def __init__( self, *, - containers: List["Container"], - os_type: Union[str, "OperatingSystemTypes"], + containers: List["_models.Container"], + os_type: Union[str, "_models.OperatingSystemTypes"], + identity: Optional["_models.ContainerGroupIdentity"] = None, + image_registry_credentials: Optional[List["_models.ImageRegistryCredential"]] = None, + restart_policy: Optional[Union[str, "_models.ContainerGroupRestartPolicy"]] = None, + ip_address: Optional["_models.IpAddress"] = None, + volumes: Optional[List["_models.Volume"]] = None, + diagnostics: Optional["_models.ContainerGroupDiagnostics"] = None, + subnet_ids: Optional[List["_models.ContainerGroupSubnetId"]] = None, + dns_config: Optional["_models.DnsConfiguration"] = None, + sku: Optional[Union[str, "_models.ContainerGroupSku"]] = None, + encryption_properties: Optional["_models.EncryptionProperties"] = None, + init_containers: Optional[List["_models.InitContainerDefinition"]] = None, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, zones: Optional[List[str]] = None, - identity: Optional["ContainerGroupIdentity"] = None, - image_registry_credentials: Optional[List["ImageRegistryCredential"]] = None, - restart_policy: Optional[Union[str, "ContainerGroupRestartPolicy"]] = None, - ip_address: Optional["IpAddress"] = None, - volumes: Optional[List["Volume"]] = None, - diagnostics: Optional["ContainerGroupDiagnostics"] = None, - subnet_ids: Optional[List["ContainerGroupSubnetId"]] = None, - dns_config: Optional["DnsConfiguration"] = None, - sku: Optional[Union[str, "ContainerGroupSku"]] = None, - encryption_properties: Optional["EncryptionProperties"] = None, - init_containers: Optional[List["InitContainerDefinition"]] = None, **kwargs ): """ - :keyword location: The resource location. - :paramtype location: str - :keyword tags: A set of tags. The resource tags. - :paramtype tags: dict[str, str] - :keyword zones: The zones for the container group. - :paramtype zones: list[str] :keyword identity: The identity of the container group, if configured. :paramtype identity: ~azure.mgmt.containerinstance.models.ContainerGroupIdentity - :keyword containers: Required. The containers within the container group. + :keyword containers: The containers within the container group. Required. :paramtype containers: list[~azure.mgmt.containerinstance.models.Container] :keyword image_registry_credentials: The image registry credentials by which the container group is created from. :paramtype image_registry_credentials: list[~azure.mgmt.containerinstance.models.ImageRegistryCredential] :keyword restart_policy: Restart policy for all containers within the container group. - - + + * ``Always`` Always restart * ``OnFailure`` Restart on failure - * ``Never`` Never restart. Possible values include: "Always", "OnFailure", "Never". + * ``Never`` Never restart. Known values are: "Always", "OnFailure", and "Never". :paramtype restart_policy: str or ~azure.mgmt.containerinstance.models.ContainerGroupRestartPolicy :keyword ip_address: The IP address type of the container group. :paramtype ip_address: ~azure.mgmt.containerinstance.models.IpAddress - :keyword os_type: Required. The operating system type required by the containers in the - container group. Possible values include: "Windows", "Linux". + :keyword os_type: The operating system type required by the containers in the container group. + Required. Known values are: "Windows" and "Linux". :paramtype os_type: str or ~azure.mgmt.containerinstance.models.OperatingSystemTypes :keyword volumes: The list of volumes that can be mounted by containers in this container group. @@ -812,14 +893,38 @@ def __init__( :paramtype subnet_ids: list[~azure.mgmt.containerinstance.models.ContainerGroupSubnetId] :keyword dns_config: The DNS config information for a container group. :paramtype dns_config: ~azure.mgmt.containerinstance.models.DnsConfiguration - :keyword sku: The SKU for a container group. Possible values include: "Standard", "Dedicated". + :keyword sku: The SKU for a container group. Known values are: "Standard" and "Dedicated". :paramtype sku: str or ~azure.mgmt.containerinstance.models.ContainerGroupSku :keyword encryption_properties: The encryption properties for a container group. :paramtype encryption_properties: ~azure.mgmt.containerinstance.models.EncryptionProperties :keyword init_containers: The init containers for a container group. :paramtype init_containers: list[~azure.mgmt.containerinstance.models.InitContainerDefinition] + :keyword location: The resource location. + :paramtype location: str + :keyword tags: The resource tags. + :paramtype tags: dict[str, str] + :keyword zones: The zones for the container group. + :paramtype zones: list[str] """ - super(ContainerGroup, self).__init__(location=location, tags=tags, zones=zones, **kwargs) + super().__init__( + location=location, + tags=tags, + zones=zones, + identity=identity, + containers=containers, + image_registry_credentials=image_registry_credentials, + restart_policy=restart_policy, + ip_address=ip_address, + os_type=os_type, + volumes=volumes, + diagnostics=diagnostics, + subnet_ids=subnet_ids, + dns_config=dns_config, + sku=sku, + encryption_properties=encryption_properties, + init_containers=init_containers, + **kwargs + ) self.identity = identity self.provisioning_state = None self.containers = containers @@ -835,9 +940,15 @@ def __init__( self.sku = sku self.encryption_properties = encryption_properties self.init_containers = init_containers + self.id = None + self.name = None + self.type = None + self.location = location + self.tags = tags + self.zones = zones -class ContainerGroupDiagnostics(msrest.serialization.Model): +class ContainerGroupDiagnostics(_serialization.Model): """Container group diagnostic information. :ivar log_analytics: Container group log analytics information. @@ -845,24 +956,19 @@ class ContainerGroupDiagnostics(msrest.serialization.Model): """ _attribute_map = { - 'log_analytics': {'key': 'logAnalytics', 'type': 'LogAnalytics'}, + "log_analytics": {"key": "logAnalytics", "type": "LogAnalytics"}, } - def __init__( - self, - *, - log_analytics: Optional["LogAnalytics"] = None, - **kwargs - ): + def __init__(self, *, log_analytics: Optional["_models.LogAnalytics"] = None, **kwargs): """ :keyword log_analytics: Container group log analytics information. :paramtype log_analytics: ~azure.mgmt.containerinstance.models.LogAnalytics """ - super(ContainerGroupDiagnostics, self).__init__(**kwargs) + super().__init__(**kwargs) self.log_analytics = log_analytics -class ContainerGroupIdentity(msrest.serialization.Model): +class ContainerGroupIdentity(_serialization.Model): """Identity for the container group. Variables are only populated by the server, and will be ignored when sending a request. @@ -875,55 +981,53 @@ class ContainerGroupIdentity(msrest.serialization.Model): :vartype tenant_id: str :ivar type: The type of identity used for the container group. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned - identities. The type 'None' will remove any identities from the container group. Possible - values include: "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned", "None". + identities. The type 'None' will remove any identities from the container group. Known values + are: "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned", and "None". :vartype type: str or ~azure.mgmt.containerinstance.models.ResourceIdentityType :ivar user_assigned_identities: The list of user identities associated with the container - group. The user identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + group. :vartype user_assigned_identities: dict[str, - ~azure.mgmt.containerinstance.models.Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties] + ~azure.mgmt.containerinstance.models.UserAssignedIdentities] """ _validation = { - 'principal_id': {'readonly': True}, - 'tenant_id': {'readonly': True}, + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, } _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'tenant_id': {'key': 'tenantId', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties}'}, + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentities}"}, } def __init__( self, *, - type: Optional[Union[str, "ResourceIdentityType"]] = None, - user_assigned_identities: Optional[Dict[str, "Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"]] = None, + type: Optional[Union[str, "_models.ResourceIdentityType"]] = None, + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentities"]] = None, **kwargs ): """ :keyword type: The type of identity used for the container group. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned - identities. The type 'None' will remove any identities from the container group. Possible - values include: "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned", "None". + identities. The type 'None' will remove any identities from the container group. Known values + are: "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned", and "None". :paramtype type: str or ~azure.mgmt.containerinstance.models.ResourceIdentityType :keyword user_assigned_identities: The list of user identities associated with the container - group. The user identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + group. :paramtype user_assigned_identities: dict[str, - ~azure.mgmt.containerinstance.models.Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties] + ~azure.mgmt.containerinstance.models.UserAssignedIdentities] """ - super(ContainerGroupIdentity, self).__init__(**kwargs) + super().__init__(**kwargs) self.principal_id = None self.tenant_id = None self.type = type self.user_assigned_identities = user_assigned_identities -class ContainerGroupListResult(msrest.serialization.Model): +class ContainerGroupListResult(_serialization.Model): """The container group list response that contains the container group properties. :ivar value: The list of container groups. @@ -933,16 +1037,12 @@ class ContainerGroupListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ContainerGroup]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ContainerGroup]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["ContainerGroup"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.ContainerGroup"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of container groups. @@ -950,12 +1050,12 @@ def __init__( :keyword next_link: The URI to fetch the next page of container groups. :paramtype next_link: str """ - super(ContainerGroupListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ContainerGroupPropertiesInstanceView(msrest.serialization.Model): +class ContainerGroupPropertiesInstanceView(_serialization.Model): """The instance view of the container group. Only valid in response. Variables are only populated by the server, and will be ignored when sending a request. @@ -967,88 +1067,78 @@ class ContainerGroupPropertiesInstanceView(msrest.serialization.Model): """ _validation = { - 'events': {'readonly': True}, - 'state': {'readonly': True}, + "events": {"readonly": True}, + "state": {"readonly": True}, } _attribute_map = { - 'events': {'key': 'events', 'type': '[Event]'}, - 'state': {'key': 'state', 'type': 'str'}, + "events": {"key": "events", "type": "[Event]"}, + "state": {"key": "state", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ContainerGroupPropertiesInstanceView, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.events = None self.state = None -class ContainerGroupSubnetId(msrest.serialization.Model): +class ContainerGroupSubnetId(_serialization.Model): """Container group subnet information. All required parameters must be populated in order to send to Azure. - :ivar id: Required. Resource ID of virtual network and subnet. + :ivar id: Resource ID of virtual network and subnet. Required. :vartype id: str :ivar name: Friendly name for the subnet. :vartype name: str """ _validation = { - 'id': {'required': True}, + "id": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - *, - id: str, - name: Optional[str] = None, - **kwargs - ): + def __init__(self, *, id: str, name: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin """ - :keyword id: Required. Resource ID of virtual network and subnet. + :keyword id: Resource ID of virtual network and subnet. Required. :paramtype id: str :keyword name: Friendly name for the subnet. :paramtype name: str """ - super(ContainerGroupSubnetId, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.name = name -class ContainerHttpGet(msrest.serialization.Model): +class ContainerHttpGet(_serialization.Model): """The container Http Get settings, for liveness or readiness probe. All required parameters must be populated in order to send to Azure. :ivar path: The path to probe. :vartype path: str - :ivar port: Required. The port number to probe. + :ivar port: The port number to probe. Required. :vartype port: int - :ivar scheme: The scheme. Possible values include: "http", "https". + :ivar scheme: The scheme. Known values are: "http" and "https". :vartype scheme: str or ~azure.mgmt.containerinstance.models.Scheme :ivar http_headers: The HTTP headers. :vartype http_headers: list[~azure.mgmt.containerinstance.models.HttpHeader] """ _validation = { - 'port': {'required': True}, + "port": {"required": True}, } _attribute_map = { - 'path': {'key': 'path', 'type': 'str'}, - 'port': {'key': 'port', 'type': 'int'}, - 'scheme': {'key': 'scheme', 'type': 'str'}, - 'http_headers': {'key': 'httpHeaders', 'type': '[HttpHeader]'}, + "path": {"key": "path", "type": "str"}, + "port": {"key": "port", "type": "int"}, + "scheme": {"key": "scheme", "type": "str"}, + "http_headers": {"key": "httpHeaders", "type": "[HttpHeader]"}, } def __init__( @@ -1056,67 +1146,62 @@ def __init__( *, port: int, path: Optional[str] = None, - scheme: Optional[Union[str, "Scheme"]] = None, - http_headers: Optional[List["HttpHeader"]] = None, + scheme: Optional[Union[str, "_models.Scheme"]] = None, + http_headers: Optional[List["_models.HttpHeader"]] = None, **kwargs ): """ :keyword path: The path to probe. :paramtype path: str - :keyword port: Required. The port number to probe. + :keyword port: The port number to probe. Required. :paramtype port: int - :keyword scheme: The scheme. Possible values include: "http", "https". + :keyword scheme: The scheme. Known values are: "http" and "https". :paramtype scheme: str or ~azure.mgmt.containerinstance.models.Scheme :keyword http_headers: The HTTP headers. :paramtype http_headers: list[~azure.mgmt.containerinstance.models.HttpHeader] """ - super(ContainerHttpGet, self).__init__(**kwargs) + super().__init__(**kwargs) self.path = path self.port = port self.scheme = scheme self.http_headers = http_headers -class ContainerPort(msrest.serialization.Model): +class ContainerPort(_serialization.Model): """The port exposed on the container instance. All required parameters must be populated in order to send to Azure. - :ivar protocol: The protocol associated with the port. Possible values include: "TCP", "UDP". + :ivar protocol: The protocol associated with the port. Known values are: "TCP" and "UDP". :vartype protocol: str or ~azure.mgmt.containerinstance.models.ContainerNetworkProtocol - :ivar port: Required. The port number exposed within the container group. + :ivar port: The port number exposed within the container group. Required. :vartype port: int """ _validation = { - 'port': {'required': True}, + "port": {"required": True}, } _attribute_map = { - 'protocol': {'key': 'protocol', 'type': 'str'}, - 'port': {'key': 'port', 'type': 'int'}, + "protocol": {"key": "protocol", "type": "str"}, + "port": {"key": "port", "type": "int"}, } def __init__( - self, - *, - port: int, - protocol: Optional[Union[str, "ContainerNetworkProtocol"]] = None, - **kwargs + self, *, port: int, protocol: Optional[Union[str, "_models.ContainerNetworkProtocol"]] = None, **kwargs ): """ - :keyword protocol: The protocol associated with the port. Possible values include: "TCP", - "UDP". + :keyword protocol: The protocol associated with the port. Known values are: "TCP" and "UDP". :paramtype protocol: str or ~azure.mgmt.containerinstance.models.ContainerNetworkProtocol - :keyword port: Required. The port number exposed within the container group. + :keyword port: The port number exposed within the container group. Required. :paramtype port: int """ - super(ContainerPort, self).__init__(**kwargs) + super().__init__(**kwargs) self.protocol = protocol self.port = port -class ContainerProbe(msrest.serialization.Model): +class ContainerProbe(_serialization.Model): """The container probe, for liveness or readiness. :ivar exec_property: The execution command to probe. @@ -1136,20 +1221,20 @@ class ContainerProbe(msrest.serialization.Model): """ _attribute_map = { - 'exec_property': {'key': 'exec', 'type': 'ContainerExec'}, - 'http_get': {'key': 'httpGet', 'type': 'ContainerHttpGet'}, - 'initial_delay_seconds': {'key': 'initialDelaySeconds', 'type': 'int'}, - 'period_seconds': {'key': 'periodSeconds', 'type': 'int'}, - 'failure_threshold': {'key': 'failureThreshold', 'type': 'int'}, - 'success_threshold': {'key': 'successThreshold', 'type': 'int'}, - 'timeout_seconds': {'key': 'timeoutSeconds', 'type': 'int'}, + "exec_property": {"key": "exec", "type": "ContainerExec"}, + "http_get": {"key": "httpGet", "type": "ContainerHttpGet"}, + "initial_delay_seconds": {"key": "initialDelaySeconds", "type": "int"}, + "period_seconds": {"key": "periodSeconds", "type": "int"}, + "failure_threshold": {"key": "failureThreshold", "type": "int"}, + "success_threshold": {"key": "successThreshold", "type": "int"}, + "timeout_seconds": {"key": "timeoutSeconds", "type": "int"}, } def __init__( self, *, - exec_property: Optional["ContainerExec"] = None, - http_get: Optional["ContainerHttpGet"] = None, + exec_property: Optional["_models.ContainerExec"] = None, + http_get: Optional["_models.ContainerHttpGet"] = None, initial_delay_seconds: Optional[int] = None, period_seconds: Optional[int] = None, failure_threshold: Optional[int] = None, @@ -1173,7 +1258,7 @@ def __init__( :keyword timeout_seconds: The timeout seconds. :paramtype timeout_seconds: int """ - super(ContainerProbe, self).__init__(**kwargs) + super().__init__(**kwargs) self.exec_property = exec_property self.http_get = http_get self.initial_delay_seconds = initial_delay_seconds @@ -1183,7 +1268,7 @@ def __init__( self.timeout_seconds = timeout_seconds -class ContainerPropertiesInstanceView(msrest.serialization.Model): +class ContainerPropertiesInstanceView(_serialization.Model): """The instance view of the container instance. Only valid in response. Variables are only populated by the server, and will be ignored when sending a request. @@ -1199,33 +1284,29 @@ class ContainerPropertiesInstanceView(msrest.serialization.Model): """ _validation = { - 'restart_count': {'readonly': True}, - 'current_state': {'readonly': True}, - 'previous_state': {'readonly': True}, - 'events': {'readonly': True}, + "restart_count": {"readonly": True}, + "current_state": {"readonly": True}, + "previous_state": {"readonly": True}, + "events": {"readonly": True}, } _attribute_map = { - 'restart_count': {'key': 'restartCount', 'type': 'int'}, - 'current_state': {'key': 'currentState', 'type': 'ContainerState'}, - 'previous_state': {'key': 'previousState', 'type': 'ContainerState'}, - 'events': {'key': 'events', 'type': '[Event]'}, + "restart_count": {"key": "restartCount", "type": "int"}, + "current_state": {"key": "currentState", "type": "ContainerState"}, + "previous_state": {"key": "previousState", "type": "ContainerState"}, + "events": {"key": "events", "type": "[Event]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ContainerPropertiesInstanceView, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.restart_count = None self.current_state = None self.previous_state = None self.events = None -class ContainerState(msrest.serialization.Model): +class ContainerState(_serialization.Model): """The container instance state. Variables are only populated by the server, and will be ignored when sending a request. @@ -1244,28 +1325,24 @@ class ContainerState(msrest.serialization.Model): """ _validation = { - 'state': {'readonly': True}, - 'start_time': {'readonly': True}, - 'exit_code': {'readonly': True}, - 'finish_time': {'readonly': True}, - 'detail_status': {'readonly': True}, + "state": {"readonly": True}, + "start_time": {"readonly": True}, + "exit_code": {"readonly": True}, + "finish_time": {"readonly": True}, + "detail_status": {"readonly": True}, } _attribute_map = { - 'state': {'key': 'state', 'type': 'str'}, - 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, - 'exit_code': {'key': 'exitCode', 'type': 'int'}, - 'finish_time': {'key': 'finishTime', 'type': 'iso-8601'}, - 'detail_status': {'key': 'detailStatus', 'type': 'str'}, + "state": {"key": "state", "type": "str"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + "exit_code": {"key": "exitCode", "type": "int"}, + "finish_time": {"key": "finishTime", "type": "iso-8601"}, + "detail_status": {"key": "detailStatus", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ContainerState, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.state = None self.start_time = None self.exit_code = None @@ -1273,12 +1350,12 @@ def __init__( self.detail_status = None -class DnsConfiguration(msrest.serialization.Model): +class DnsConfiguration(_serialization.Model): """DNS configuration for the container group. All required parameters must be populated in order to send to Azure. - :ivar name_servers: Required. The DNS servers for the container group. + :ivar name_servers: The DNS servers for the container group. Required. :vartype name_servers: list[str] :ivar search_domains: The DNS search domains for hostname lookup in the container group. :vartype search_domains: str @@ -1287,90 +1364,78 @@ class DnsConfiguration(msrest.serialization.Model): """ _validation = { - 'name_servers': {'required': True}, + "name_servers": {"required": True}, } _attribute_map = { - 'name_servers': {'key': 'nameServers', 'type': '[str]'}, - 'search_domains': {'key': 'searchDomains', 'type': 'str'}, - 'options': {'key': 'options', 'type': 'str'}, + "name_servers": {"key": "nameServers", "type": "[str]"}, + "search_domains": {"key": "searchDomains", "type": "str"}, + "options": {"key": "options", "type": "str"}, } def __init__( - self, - *, - name_servers: List[str], - search_domains: Optional[str] = None, - options: Optional[str] = None, - **kwargs + self, *, name_servers: List[str], search_domains: Optional[str] = None, options: Optional[str] = None, **kwargs ): """ - :keyword name_servers: Required. The DNS servers for the container group. + :keyword name_servers: The DNS servers for the container group. Required. :paramtype name_servers: list[str] :keyword search_domains: The DNS search domains for hostname lookup in the container group. :paramtype search_domains: str :keyword options: The DNS options for the container group. :paramtype options: str """ - super(DnsConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.name_servers = name_servers self.search_domains = search_domains self.options = options -class EncryptionProperties(msrest.serialization.Model): +class EncryptionProperties(_serialization.Model): """The container group encryption properties. All required parameters must be populated in order to send to Azure. - :ivar vault_base_url: Required. The keyvault base url. + :ivar vault_base_url: The keyvault base url. Required. :vartype vault_base_url: str - :ivar key_name: Required. The encryption key name. + :ivar key_name: The encryption key name. Required. :vartype key_name: str - :ivar key_version: Required. The encryption key version. + :ivar key_version: The encryption key version. Required. :vartype key_version: str """ _validation = { - 'vault_base_url': {'required': True}, - 'key_name': {'required': True}, - 'key_version': {'required': True}, + "vault_base_url": {"required": True}, + "key_name": {"required": True}, + "key_version": {"required": True}, } _attribute_map = { - 'vault_base_url': {'key': 'vaultBaseUrl', 'type': 'str'}, - 'key_name': {'key': 'keyName', 'type': 'str'}, - 'key_version': {'key': 'keyVersion', 'type': 'str'}, + "vault_base_url": {"key": "vaultBaseUrl", "type": "str"}, + "key_name": {"key": "keyName", "type": "str"}, + "key_version": {"key": "keyVersion", "type": "str"}, } - def __init__( - self, - *, - vault_base_url: str, - key_name: str, - key_version: str, - **kwargs - ): + def __init__(self, *, vault_base_url: str, key_name: str, key_version: str, **kwargs): """ - :keyword vault_base_url: Required. The keyvault base url. + :keyword vault_base_url: The keyvault base url. Required. :paramtype vault_base_url: str - :keyword key_name: Required. The encryption key name. + :keyword key_name: The encryption key name. Required. :paramtype key_name: str - :keyword key_version: Required. The encryption key version. + :keyword key_version: The encryption key version. Required. :paramtype key_version: str """ - super(EncryptionProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.vault_base_url = vault_base_url self.key_name = key_name self.key_version = key_version -class EnvironmentVariable(msrest.serialization.Model): +class EnvironmentVariable(_serialization.Model): """The environment variable to set within the container instance. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the environment variable. + :ivar name: The name of the environment variable. Required. :vartype name: str :ivar value: The value of the environment variable. :vartype value: str @@ -1379,38 +1444,31 @@ class EnvironmentVariable(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, - 'secure_value': {'key': 'secureValue', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "secure_value": {"key": "secureValue", "type": "str"}, } - def __init__( - self, - *, - name: str, - value: Optional[str] = None, - secure_value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: str, value: Optional[str] = None, secure_value: Optional[str] = None, **kwargs): """ - :keyword name: Required. The name of the environment variable. + :keyword name: The name of the environment variable. Required. :paramtype name: str :keyword value: The value of the environment variable. :paramtype value: str :keyword secure_value: The value of the secure environment variable. :paramtype secure_value: str """ - super(EnvironmentVariable, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value self.secure_value = secure_value -class Event(msrest.serialization.Model): +class Event(_serialization.Model): """A container group or container instance event. Variables are only populated by the server, and will be ignored when sending a request. @@ -1430,30 +1488,26 @@ class Event(msrest.serialization.Model): """ _validation = { - 'count': {'readonly': True}, - 'first_timestamp': {'readonly': True}, - 'last_timestamp': {'readonly': True}, - 'name': {'readonly': True}, - 'message': {'readonly': True}, - 'type': {'readonly': True}, + "count": {"readonly": True}, + "first_timestamp": {"readonly": True}, + "last_timestamp": {"readonly": True}, + "name": {"readonly": True}, + "message": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'count': {'key': 'count', 'type': 'int'}, - 'first_timestamp': {'key': 'firstTimestamp', 'type': 'iso-8601'}, - 'last_timestamp': {'key': 'lastTimestamp', 'type': 'iso-8601'}, - 'name': {'key': 'name', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "count": {"key": "count", "type": "int"}, + "first_timestamp": {"key": "firstTimestamp", "type": "iso-8601"}, + "last_timestamp": {"key": "lastTimestamp", "type": "iso-8601"}, + "name": {"key": "name", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Event, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.count = None self.first_timestamp = None self.last_timestamp = None @@ -1462,7 +1516,7 @@ def __init__( self.type = None -class GitRepoVolume(msrest.serialization.Model): +class GitRepoVolume(_serialization.Model): """Represents a volume that is populated with the contents of a git repository. All required parameters must be populated in order to send to Azure. @@ -1471,88 +1525,74 @@ class GitRepoVolume(msrest.serialization.Model): supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name. :vartype directory: str - :ivar repository: Required. Repository URL. + :ivar repository: Repository URL. Required. :vartype repository: str :ivar revision: Commit hash for the specified revision. :vartype revision: str """ _validation = { - 'repository': {'required': True}, + "repository": {"required": True}, } _attribute_map = { - 'directory': {'key': 'directory', 'type': 'str'}, - 'repository': {'key': 'repository', 'type': 'str'}, - 'revision': {'key': 'revision', 'type': 'str'}, + "directory": {"key": "directory", "type": "str"}, + "repository": {"key": "repository", "type": "str"}, + "revision": {"key": "revision", "type": "str"}, } - def __init__( - self, - *, - repository: str, - directory: Optional[str] = None, - revision: Optional[str] = None, - **kwargs - ): + def __init__(self, *, repository: str, directory: Optional[str] = None, revision: Optional[str] = None, **kwargs): """ :keyword directory: Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name. :paramtype directory: str - :keyword repository: Required. Repository URL. + :keyword repository: Repository URL. Required. :paramtype repository: str :keyword revision: Commit hash for the specified revision. :paramtype revision: str """ - super(GitRepoVolume, self).__init__(**kwargs) + super().__init__(**kwargs) self.directory = directory self.repository = repository self.revision = revision -class GpuResource(msrest.serialization.Model): +class GpuResource(_serialization.Model): """The GPU resource. All required parameters must be populated in order to send to Azure. - :ivar count: Required. The count of the GPU resource. + :ivar count: The count of the GPU resource. Required. :vartype count: int - :ivar sku: Required. The SKU of the GPU resource. Possible values include: "K80", "P100", - "V100". + :ivar sku: The SKU of the GPU resource. Required. Known values are: "K80", "P100", and "V100". :vartype sku: str or ~azure.mgmt.containerinstance.models.GpuSku """ _validation = { - 'count': {'required': True}, - 'sku': {'required': True}, + "count": {"required": True}, + "sku": {"required": True}, } _attribute_map = { - 'count': {'key': 'count', 'type': 'int'}, - 'sku': {'key': 'sku', 'type': 'str'}, + "count": {"key": "count", "type": "int"}, + "sku": {"key": "sku", "type": "str"}, } - def __init__( - self, - *, - count: int, - sku: Union[str, "GpuSku"], - **kwargs - ): + def __init__(self, *, count: int, sku: Union[str, "_models.GpuSku"], **kwargs): """ - :keyword count: Required. The count of the GPU resource. + :keyword count: The count of the GPU resource. Required. :paramtype count: int - :keyword sku: Required. The SKU of the GPU resource. Possible values include: "K80", "P100", + :keyword sku: The SKU of the GPU resource. Required. Known values are: "K80", "P100", and "V100". :paramtype sku: str or ~azure.mgmt.containerinstance.models.GpuSku """ - super(GpuResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.count = count self.sku = sku -class HttpHeader(msrest.serialization.Model): +class HttpHeader(_serialization.Model): """The HTTP header. :ivar name: The header name. @@ -1562,37 +1602,31 @@ class HttpHeader(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs): """ :keyword name: The header name. :paramtype name: str :keyword value: The header value. :paramtype value: str """ - super(HttpHeader, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value -class ImageRegistryCredential(msrest.serialization.Model): +class ImageRegistryCredential(_serialization.Model): """Image registry credential. All required parameters must be populated in order to send to Azure. - :ivar server: Required. The Docker image registry server without a protocol such as "http" and - "https". + :ivar server: The Docker image registry server without a protocol such as "http" and "https". + Required. :vartype server: str - :ivar username: Required. The username for the private registry. + :ivar username: The username for the private registry. :vartype username: str :ivar password: The password for the private registry. :vartype password: str @@ -1603,33 +1637,32 @@ class ImageRegistryCredential(msrest.serialization.Model): """ _validation = { - 'server': {'required': True}, - 'username': {'required': True}, + "server": {"required": True}, } _attribute_map = { - 'server': {'key': 'server', 'type': 'str'}, - 'username': {'key': 'username', 'type': 'str'}, - 'password': {'key': 'password', 'type': 'str'}, - 'identity': {'key': 'identity', 'type': 'str'}, - 'identity_url': {'key': 'identityUrl', 'type': 'str'}, + "server": {"key": "server", "type": "str"}, + "username": {"key": "username", "type": "str"}, + "password": {"key": "password", "type": "str"}, + "identity": {"key": "identity", "type": "str"}, + "identity_url": {"key": "identityUrl", "type": "str"}, } def __init__( self, *, server: str, - username: str, + username: Optional[str] = None, password: Optional[str] = None, identity: Optional[str] = None, identity_url: Optional[str] = None, **kwargs ): """ - :keyword server: Required. The Docker image registry server without a protocol such as "http" - and "https". + :keyword server: The Docker image registry server without a protocol such as "http" and + "https". Required. :paramtype server: str - :keyword username: Required. The username for the private registry. + :keyword username: The username for the private registry. :paramtype username: str :keyword password: The password for the private registry. :paramtype password: str @@ -1638,7 +1671,7 @@ def __init__( :keyword identity_url: The identity URL for the private registry. :paramtype identity_url: str """ - super(ImageRegistryCredential, self).__init__(**kwargs) + super().__init__(**kwargs) self.server = server self.username = username self.password = password @@ -1646,14 +1679,14 @@ def __init__( self.identity_url = identity_url -class InitContainerDefinition(msrest.serialization.Model): +class InitContainerDefinition(_serialization.Model): """The init container definition. 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: Required. The name for the init container. + :ivar name: The name for the init container. Required. :vartype name: str :ivar image: The image of the init container. :vartype image: str @@ -1669,17 +1702,17 @@ class InitContainerDefinition(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, - 'instance_view': {'readonly': True}, + "name": {"required": True}, + "instance_view": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'image': {'key': 'properties.image', 'type': 'str'}, - 'command': {'key': 'properties.command', 'type': '[str]'}, - 'environment_variables': {'key': 'properties.environmentVariables', 'type': '[EnvironmentVariable]'}, - 'instance_view': {'key': 'properties.instanceView', 'type': 'InitContainerPropertiesDefinitionInstanceView'}, - 'volume_mounts': {'key': 'properties.volumeMounts', 'type': '[VolumeMount]'}, + "name": {"key": "name", "type": "str"}, + "image": {"key": "properties.image", "type": "str"}, + "command": {"key": "properties.command", "type": "[str]"}, + "environment_variables": {"key": "properties.environmentVariables", "type": "[EnvironmentVariable]"}, + "instance_view": {"key": "properties.instanceView", "type": "InitContainerPropertiesDefinitionInstanceView"}, + "volume_mounts": {"key": "properties.volumeMounts", "type": "[VolumeMount]"}, } def __init__( @@ -1688,12 +1721,12 @@ def __init__( name: str, image: Optional[str] = None, command: Optional[List[str]] = None, - environment_variables: Optional[List["EnvironmentVariable"]] = None, - volume_mounts: Optional[List["VolumeMount"]] = None, + environment_variables: Optional[List["_models.EnvironmentVariable"]] = None, + volume_mounts: Optional[List["_models.VolumeMount"]] = None, **kwargs ): """ - :keyword name: Required. The name for the init container. + :keyword name: The name for the init container. Required. :paramtype name: str :keyword image: The image of the init container. :paramtype image: str @@ -1705,7 +1738,7 @@ def __init__( :keyword volume_mounts: The volume mounts available to the init container. :paramtype volume_mounts: list[~azure.mgmt.containerinstance.models.VolumeMount] """ - super(InitContainerDefinition, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.image = image self.command = command @@ -1714,7 +1747,7 @@ def __init__( self.volume_mounts = volume_mounts -class InitContainerPropertiesDefinitionInstanceView(msrest.serialization.Model): +class InitContainerPropertiesDefinitionInstanceView(_serialization.Model): """The instance view of the init container. Only valid in response. Variables are only populated by the server, and will be ignored when sending a request. @@ -1730,115 +1763,125 @@ class InitContainerPropertiesDefinitionInstanceView(msrest.serialization.Model): """ _validation = { - 'restart_count': {'readonly': True}, - 'current_state': {'readonly': True}, - 'previous_state': {'readonly': True}, - 'events': {'readonly': True}, + "restart_count": {"readonly": True}, + "current_state": {"readonly": True}, + "previous_state": {"readonly": True}, + "events": {"readonly": True}, } _attribute_map = { - 'restart_count': {'key': 'restartCount', 'type': 'int'}, - 'current_state': {'key': 'currentState', 'type': 'ContainerState'}, - 'previous_state': {'key': 'previousState', 'type': 'ContainerState'}, - 'events': {'key': 'events', 'type': '[Event]'}, + "restart_count": {"key": "restartCount", "type": "int"}, + "current_state": {"key": "currentState", "type": "ContainerState"}, + "previous_state": {"key": "previousState", "type": "ContainerState"}, + "events": {"key": "events", "type": "[Event]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(InitContainerPropertiesDefinitionInstanceView, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.restart_count = None self.current_state = None self.previous_state = None self.events = None -class IpAddress(msrest.serialization.Model): +class IpAddress(_serialization.Model): """IP address for the container group. 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 ports: Required. The list of ports exposed on the container group. + :ivar ports: The list of ports exposed on the container group. Required. :vartype ports: list[~azure.mgmt.containerinstance.models.Port] - :ivar type: Required. Specifies if the IP is exposed to the public internet or private VNET. - Possible values include: "Public", "Private". + :ivar type: Specifies if the IP is exposed to the public internet or private VNET. Required. + Known values are: "Public" and "Private". :vartype type: str or ~azure.mgmt.containerinstance.models.ContainerGroupIpAddressType :ivar ip: The IP exposed to the public internet. :vartype ip: str :ivar dns_name_label: The Dns name label for the IP. :vartype dns_name_label: str - :ivar dns_name_label_reuse_policy: The value representing the security enum. Possible values - include: "Unsecure", "TenantReuse", "SubscriptionReuse", "ResourceGroupReuse", "Noreuse". - :vartype dns_name_label_reuse_policy: str or - ~azure.mgmt.containerinstance.models.AutoGeneratedDomainNameLabelScope + :ivar auto_generated_domain_name_label_scope: The value representing the security enum. The + 'Unsecure' value is the default value if not selected and means the object's domain name label + is not secured against subdomain takeover. The 'TenantReuse' value is the default value if + selected and means the object's domain name label can be reused within the same tenant. The + 'SubscriptionReuse' value means the object's domain name label can be reused within the same + subscription. The 'ResourceGroupReuse' value means the object's domain name label can be reused + within the same resource group. The 'NoReuse' value means the object's domain name label cannot + be reused within the same resource group, subscription, or tenant. Known values are: + "Unsecure", "TenantReuse", "SubscriptionReuse", "ResourceGroupReuse", and "Noreuse". + :vartype auto_generated_domain_name_label_scope: str or + ~azure.mgmt.containerinstance.models.DnsNameLabelReusePolicy :ivar fqdn: The FQDN for the IP. :vartype fqdn: str """ _validation = { - 'ports': {'required': True}, - 'type': {'required': True}, - 'fqdn': {'readonly': True}, + "ports": {"required": True}, + "type": {"required": True}, + "fqdn": {"readonly": True}, } _attribute_map = { - 'ports': {'key': 'ports', 'type': '[Port]'}, - 'type': {'key': 'type', 'type': 'str'}, - 'ip': {'key': 'ip', 'type': 'str'}, - 'dns_name_label': {'key': 'dnsNameLabel', 'type': 'str'}, - 'dns_name_label_reuse_policy': {'key': 'dnsNameLabelReusePolicy', 'type': 'str'}, - 'fqdn': {'key': 'fqdn', 'type': 'str'}, + "ports": {"key": "ports", "type": "[Port]"}, + "type": {"key": "type", "type": "str"}, + "ip": {"key": "ip", "type": "str"}, + "dns_name_label": {"key": "dnsNameLabel", "type": "str"}, + "auto_generated_domain_name_label_scope": {"key": "autoGeneratedDomainNameLabelScope", "type": "str"}, + "fqdn": {"key": "fqdn", "type": "str"}, } def __init__( self, *, - ports: List["Port"], - type: Union[str, "ContainerGroupIpAddressType"], + ports: List["_models.Port"], + type: Union[str, "_models.ContainerGroupIpAddressType"], ip: Optional[str] = None, dns_name_label: Optional[str] = None, - dns_name_label_reuse_policy: Optional[Union[str, "AutoGeneratedDomainNameLabelScope"]] = None, + auto_generated_domain_name_label_scope: Union[str, "_models.DnsNameLabelReusePolicy"] = "Unsecure", **kwargs ): """ - :keyword ports: Required. The list of ports exposed on the container group. + :keyword ports: The list of ports exposed on the container group. Required. :paramtype ports: list[~azure.mgmt.containerinstance.models.Port] - :keyword type: Required. Specifies if the IP is exposed to the public internet or private VNET. - Possible values include: "Public", "Private". + :keyword type: Specifies if the IP is exposed to the public internet or private VNET. Required. + Known values are: "Public" and "Private". :paramtype type: str or ~azure.mgmt.containerinstance.models.ContainerGroupIpAddressType :keyword ip: The IP exposed to the public internet. :paramtype ip: str :keyword dns_name_label: The Dns name label for the IP. :paramtype dns_name_label: str - :keyword dns_name_label_reuse_policy: The value representing the security enum. Possible values - include: "Unsecure", "TenantReuse", "SubscriptionReuse", "ResourceGroupReuse", "Noreuse". - :paramtype dns_name_label_reuse_policy: str or - ~azure.mgmt.containerinstance.models.AutoGeneratedDomainNameLabelScope - """ - super(IpAddress, self).__init__(**kwargs) + :keyword auto_generated_domain_name_label_scope: The value representing the security enum. The + 'Unsecure' value is the default value if not selected and means the object's domain name label + is not secured against subdomain takeover. The 'TenantReuse' value is the default value if + selected and means the object's domain name label can be reused within the same tenant. The + 'SubscriptionReuse' value means the object's domain name label can be reused within the same + subscription. The 'ResourceGroupReuse' value means the object's domain name label can be reused + within the same resource group. The 'NoReuse' value means the object's domain name label cannot + be reused within the same resource group, subscription, or tenant. Known values are: + "Unsecure", "TenantReuse", "SubscriptionReuse", "ResourceGroupReuse", and "Noreuse". + :paramtype auto_generated_domain_name_label_scope: str or + ~azure.mgmt.containerinstance.models.DnsNameLabelReusePolicy + """ + super().__init__(**kwargs) self.ports = ports self.type = type self.ip = ip self.dns_name_label = dns_name_label - self.dns_name_label_reuse_policy = dns_name_label_reuse_policy + self.auto_generated_domain_name_label_scope = auto_generated_domain_name_label_scope self.fqdn = None -class LogAnalytics(msrest.serialization.Model): +class LogAnalytics(_serialization.Model): """Container group log analytics information. All required parameters must be populated in order to send to Azure. - :ivar workspace_id: Required. The workspace id for log analytics. + :ivar workspace_id: The workspace id for log analytics. Required. :vartype workspace_id: str - :ivar workspace_key: Required. The workspace key for log analytics. + :ivar workspace_key: The workspace key for log analytics. Required. :vartype workspace_key: str - :ivar log_type: The log type to be used. Possible values include: "ContainerInsights", + :ivar log_type: The log type to be used. Known values are: "ContainerInsights" and "ContainerInstanceLogs". :vartype log_type: str or ~azure.mgmt.containerinstance.models.LogAnalyticsLogType :ivar metadata: Metadata for log analytics. @@ -1848,16 +1891,16 @@ class LogAnalytics(msrest.serialization.Model): """ _validation = { - 'workspace_id': {'required': True}, - 'workspace_key': {'required': True}, + "workspace_id": {"required": True}, + "workspace_key": {"required": True}, } _attribute_map = { - 'workspace_id': {'key': 'workspaceId', 'type': 'str'}, - 'workspace_key': {'key': 'workspaceKey', 'type': 'str'}, - 'log_type': {'key': 'logType', 'type': 'str'}, - 'metadata': {'key': 'metadata', 'type': '{str}'}, - 'workspace_resource_id': {'key': 'workspaceResourceId', 'type': 'str'}, + "workspace_id": {"key": "workspaceId", "type": "str"}, + "workspace_key": {"key": "workspaceKey", "type": "str"}, + "log_type": {"key": "logType", "type": "str"}, + "metadata": {"key": "metadata", "type": "{str}"}, + "workspace_resource_id": {"key": "workspaceResourceId", "type": "str"}, } def __init__( @@ -1865,17 +1908,17 @@ def __init__( *, workspace_id: str, workspace_key: str, - log_type: Optional[Union[str, "LogAnalyticsLogType"]] = None, + log_type: Optional[Union[str, "_models.LogAnalyticsLogType"]] = None, metadata: Optional[Dict[str, str]] = None, workspace_resource_id: Optional[str] = None, **kwargs ): """ - :keyword workspace_id: Required. The workspace id for log analytics. + :keyword workspace_id: The workspace id for log analytics. Required. :paramtype workspace_id: str - :keyword workspace_key: Required. The workspace key for log analytics. + :keyword workspace_key: The workspace key for log analytics. Required. :paramtype workspace_key: str - :keyword log_type: The log type to be used. Possible values include: "ContainerInsights", + :keyword log_type: The log type to be used. Known values are: "ContainerInsights" and "ContainerInstanceLogs". :paramtype log_type: str or ~azure.mgmt.containerinstance.models.LogAnalyticsLogType :keyword metadata: Metadata for log analytics. @@ -1883,7 +1926,7 @@ def __init__( :keyword workspace_resource_id: The workspace resource id for log analytics. :paramtype workspace_resource_id: str """ - super(LogAnalytics, self).__init__(**kwargs) + super().__init__(**kwargs) self.workspace_id = workspace_id self.workspace_key = workspace_key self.log_type = log_type @@ -1891,7 +1934,7 @@ def __init__( self.workspace_resource_id = workspace_resource_id -class Logs(msrest.serialization.Model): +class Logs(_serialization.Model): """The logs. :ivar content: The content of the log. @@ -1899,80 +1942,73 @@ class Logs(msrest.serialization.Model): """ _attribute_map = { - 'content': {'key': 'content', 'type': 'str'}, + "content": {"key": "content", "type": "str"}, } - def __init__( - self, - *, - content: Optional[str] = None, - **kwargs - ): + def __init__(self, *, content: Optional[str] = None, **kwargs): """ :keyword content: The content of the log. :paramtype content: str """ - super(Logs, self).__init__(**kwargs) + super().__init__(**kwargs) self.content = content -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """An operation for Azure Container Instance service. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the operation. + :ivar name: The name of the operation. Required. :vartype name: str - :ivar display: Required. The display information of the operation. + :ivar display: The display information of the operation. Required. :vartype display: ~azure.mgmt.containerinstance.models.OperationDisplay :ivar properties: The additional properties. - :vartype properties: any - :ivar origin: The intended executor of the operation. Possible values include: "User", - "System". + :vartype properties: JSON + :ivar origin: The intended executor of the operation. Known values are: "User" and "System". :vartype origin: str or ~azure.mgmt.containerinstance.models.ContainerInstanceOperationsOrigin """ _validation = { - 'name': {'required': True}, - 'display': {'required': True}, + "name": {"required": True}, + "display": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'properties': {'key': 'properties', 'type': 'object'}, - 'origin': {'key': 'origin', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "properties": {"key": "properties", "type": "object"}, + "origin": {"key": "origin", "type": "str"}, } def __init__( self, *, name: str, - display: "OperationDisplay", - properties: Optional[Any] = None, - origin: Optional[Union[str, "ContainerInstanceOperationsOrigin"]] = None, + display: "_models.OperationDisplay", + properties: Optional[JSON] = None, + origin: Optional[Union[str, "_models.ContainerInstanceOperationsOrigin"]] = None, **kwargs ): """ - :keyword name: Required. The name of the operation. + :keyword name: The name of the operation. Required. :paramtype name: str - :keyword display: Required. The display information of the operation. + :keyword display: The display information of the operation. Required. :paramtype display: ~azure.mgmt.containerinstance.models.OperationDisplay :keyword properties: The additional properties. - :paramtype properties: any - :keyword origin: The intended executor of the operation. Possible values include: "User", - "System". + :paramtype properties: JSON + :keyword origin: The intended executor of the operation. Known values are: "User" and "System". :paramtype origin: str or ~azure.mgmt.containerinstance.models.ContainerInstanceOperationsOrigin """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.display = display self.properties = properties self.origin = origin -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The display information of the operation. :ivar provider: The name of the provider of the operation. @@ -1986,10 +2022,10 @@ class OperationDisplay(msrest.serialization.Model): """ _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__( @@ -2011,14 +2047,14 @@ def __init__( :keyword description: The description of the operation. :paramtype description: str """ - super(OperationDisplay, self).__init__(**kwargs) + super().__init__(**kwargs) self.provider = provider self.resource = resource self.operation = operation self.description = description -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """The operation list response that contains all operations for Azure Container Instance service. :ivar value: The list of operations. @@ -2028,68 +2064,57 @@ class OperationListResult(msrest.serialization.Model): """ _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 - ): + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): """ :keyword value: The list of operations. :paramtype value: list[~azure.mgmt.containerinstance.models.Operation] :keyword next_link: The URI to fetch the next page of operations. :paramtype next_link: str """ - super(OperationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class Port(msrest.serialization.Model): +class Port(_serialization.Model): """The port exposed on the container group. All required parameters must be populated in order to send to Azure. - :ivar protocol: The protocol associated with the port. Possible values include: "TCP", "UDP". + :ivar protocol: The protocol associated with the port. Known values are: "TCP" and "UDP". :vartype protocol: str or ~azure.mgmt.containerinstance.models.ContainerGroupNetworkProtocol - :ivar port: Required. The port number. + :ivar port: The port number. Required. :vartype port: int """ _validation = { - 'port': {'required': True}, + "port": {"required": True}, } _attribute_map = { - 'protocol': {'key': 'protocol', 'type': 'str'}, - 'port': {'key': 'port', 'type': 'int'}, + "protocol": {"key": "protocol", "type": "str"}, + "port": {"key": "port", "type": "int"}, } def __init__( - self, - *, - port: int, - protocol: Optional[Union[str, "ContainerGroupNetworkProtocol"]] = None, - **kwargs + self, *, port: int, protocol: Optional[Union[str, "_models.ContainerGroupNetworkProtocol"]] = None, **kwargs ): """ - :keyword protocol: The protocol associated with the port. Possible values include: "TCP", - "UDP". + :keyword protocol: The protocol associated with the port. Known values are: "TCP" and "UDP". :paramtype protocol: str or ~azure.mgmt.containerinstance.models.ContainerGroupNetworkProtocol - :keyword port: Required. The port number. + :keyword port: The port number. Required. :paramtype port: int """ - super(Port, self).__init__(**kwargs) + super().__init__(**kwargs) self.protocol = protocol self.port = port -class ResourceLimits(msrest.serialization.Model): +class ResourceLimits(_serialization.Model): """The resource limits. :ivar memory_in_gb: The memory limit in GB of this container instance. @@ -2101,9 +2126,9 @@ class ResourceLimits(msrest.serialization.Model): """ _attribute_map = { - 'memory_in_gb': {'key': 'memoryInGB', 'type': 'float'}, - 'cpu': {'key': 'cpu', 'type': 'float'}, - 'gpu': {'key': 'gpu', 'type': 'GpuResource'}, + "memory_in_gb": {"key": "memoryInGB", "type": "float"}, + "cpu": {"key": "cpu", "type": "float"}, + "gpu": {"key": "gpu", "type": "GpuResource"}, } def __init__( @@ -2111,7 +2136,7 @@ def __init__( *, memory_in_gb: Optional[float] = None, cpu: Optional[float] = None, - gpu: Optional["GpuResource"] = None, + gpu: Optional["_models.GpuResource"] = None, **kwargs ): """ @@ -2122,101 +2147,92 @@ def __init__( :keyword gpu: The GPU limit of this container instance. :paramtype gpu: ~azure.mgmt.containerinstance.models.GpuResource """ - super(ResourceLimits, self).__init__(**kwargs) + super().__init__(**kwargs) self.memory_in_gb = memory_in_gb self.cpu = cpu self.gpu = gpu -class ResourceRequests(msrest.serialization.Model): +class ResourceRequests(_serialization.Model): """The resource requests. All required parameters must be populated in order to send to Azure. - :ivar memory_in_gb: Required. The memory request in GB of this container instance. + :ivar memory_in_gb: The memory request in GB of this container instance. Required. :vartype memory_in_gb: float - :ivar cpu: Required. The CPU request of this container instance. + :ivar cpu: The CPU request of this container instance. Required. :vartype cpu: float :ivar gpu: The GPU request of this container instance. :vartype gpu: ~azure.mgmt.containerinstance.models.GpuResource """ _validation = { - 'memory_in_gb': {'required': True}, - 'cpu': {'required': True}, + "memory_in_gb": {"required": True}, + "cpu": {"required": True}, } _attribute_map = { - 'memory_in_gb': {'key': 'memoryInGB', 'type': 'float'}, - 'cpu': {'key': 'cpu', 'type': 'float'}, - 'gpu': {'key': 'gpu', 'type': 'GpuResource'}, + "memory_in_gb": {"key": "memoryInGB", "type": "float"}, + "cpu": {"key": "cpu", "type": "float"}, + "gpu": {"key": "gpu", "type": "GpuResource"}, } - def __init__( - self, - *, - memory_in_gb: float, - cpu: float, - gpu: Optional["GpuResource"] = None, - **kwargs - ): + def __init__(self, *, memory_in_gb: float, cpu: float, gpu: Optional["_models.GpuResource"] = None, **kwargs): """ - :keyword memory_in_gb: Required. The memory request in GB of this container instance. + :keyword memory_in_gb: The memory request in GB of this container instance. Required. :paramtype memory_in_gb: float - :keyword cpu: Required. The CPU request of this container instance. + :keyword cpu: The CPU request of this container instance. Required. :paramtype cpu: float :keyword gpu: The GPU request of this container instance. :paramtype gpu: ~azure.mgmt.containerinstance.models.GpuResource """ - super(ResourceRequests, self).__init__(**kwargs) + super().__init__(**kwargs) self.memory_in_gb = memory_in_gb self.cpu = cpu self.gpu = gpu -class ResourceRequirements(msrest.serialization.Model): +class ResourceRequirements(_serialization.Model): """The resource requirements. All required parameters must be populated in order to send to Azure. - :ivar requests: Required. The resource requests of this container instance. + :ivar requests: The resource requests of this container instance. Required. :vartype requests: ~azure.mgmt.containerinstance.models.ResourceRequests :ivar limits: The resource limits of this container instance. :vartype limits: ~azure.mgmt.containerinstance.models.ResourceLimits """ _validation = { - 'requests': {'required': True}, + "requests": {"required": True}, } _attribute_map = { - 'requests': {'key': 'requests', 'type': 'ResourceRequests'}, - 'limits': {'key': 'limits', 'type': 'ResourceLimits'}, + "requests": {"key": "requests", "type": "ResourceRequests"}, + "limits": {"key": "limits", "type": "ResourceLimits"}, } def __init__( - self, - *, - requests: "ResourceRequests", - limits: Optional["ResourceLimits"] = None, - **kwargs + self, *, requests: "_models.ResourceRequests", limits: Optional["_models.ResourceLimits"] = None, **kwargs ): """ - :keyword requests: Required. The resource requests of this container instance. + :keyword requests: The resource requests of this container instance. Required. :paramtype requests: ~azure.mgmt.containerinstance.models.ResourceRequests :keyword limits: The resource limits of this container instance. :paramtype limits: ~azure.mgmt.containerinstance.models.ResourceLimits """ - super(ResourceRequirements, self).__init__(**kwargs) + super().__init__(**kwargs) self.requests = requests self.limits = limits -class Usage(msrest.serialization.Model): +class Usage(_serialization.Model): """A single usage result. Variables are only populated by the server, and will be ignored when sending a request. + :ivar id: Id of the usage result. + :vartype id: str :ivar unit: Unit of the usage result. :vartype unit: str :ivar current_value: The current usage of the resource. @@ -2228,33 +2244,32 @@ class Usage(msrest.serialization.Model): """ _validation = { - 'unit': {'readonly': True}, - 'current_value': {'readonly': True}, - 'limit': {'readonly': True}, - 'name': {'readonly': True}, + "id": {"readonly": True}, + "unit": {"readonly": True}, + "current_value": {"readonly": True}, + "limit": {"readonly": True}, + "name": {"readonly": True}, } _attribute_map = { - 'unit': {'key': 'unit', 'type': 'str'}, - 'current_value': {'key': 'currentValue', 'type': 'int'}, - 'limit': {'key': 'limit', 'type': 'int'}, - 'name': {'key': 'name', 'type': 'UsageName'}, + "id": {"key": "id", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "current_value": {"key": "currentValue", "type": "int"}, + "limit": {"key": "limit", "type": "int"}, + "name": {"key": "name", "type": "UsageName"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Usage, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None self.unit = None self.current_value = None self.limit = None self.name = None -class UsageListResult(msrest.serialization.Model): +class UsageListResult(_serialization.Model): """The response containing the usage data. Variables are only populated by the server, and will be ignored when sending a request. @@ -2264,24 +2279,20 @@ class UsageListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, + "value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Usage]'}, + "value": {"key": "value", "type": "[Usage]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(UsageListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None -class UsageName(msrest.serialization.Model): +class UsageName(_serialization.Model): """The name object of the resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2293,37 +2304,61 @@ class UsageName(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'localized_value': {'readonly': True}, + "value": {"readonly": True}, + "localized_value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': 'str'}, - 'localized_value': {'key': 'localizedValue', 'type': 'str'}, + "value": {"key": "value", "type": "str"}, + "localized_value": {"key": "localizedValue", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(UsageName, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.localized_value = None -class Volume(msrest.serialization.Model): +class UserAssignedIdentities(_serialization.Model): + """The list of user identities associated with the container group. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of user assigned identity. + :vartype principal_id: str + :ivar client_id: The client id of user assigned identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.principal_id = None + self.client_id = None + + +class Volume(_serialization.Model): """The properties of the volume. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the volume. + :ivar name: The name of the volume. Required. :vartype name: str :ivar azure_file: The Azure File volume. :vartype azure_file: ~azure.mgmt.containerinstance.models.AzureFileVolume :ivar empty_dir: The empty directory volume. - :vartype empty_dir: any + :vartype empty_dir: JSON :ivar secret: The secret volume. :vartype secret: dict[str, str] :ivar git_repo: The git repo volume. @@ -2331,40 +2366,40 @@ class Volume(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'azure_file': {'key': 'azureFile', 'type': 'AzureFileVolume'}, - 'empty_dir': {'key': 'emptyDir', 'type': 'object'}, - 'secret': {'key': 'secret', 'type': '{str}'}, - 'git_repo': {'key': 'gitRepo', 'type': 'GitRepoVolume'}, + "name": {"key": "name", "type": "str"}, + "azure_file": {"key": "azureFile", "type": "AzureFileVolume"}, + "empty_dir": {"key": "emptyDir", "type": "object"}, + "secret": {"key": "secret", "type": "{str}"}, + "git_repo": {"key": "gitRepo", "type": "GitRepoVolume"}, } def __init__( self, *, name: str, - azure_file: Optional["AzureFileVolume"] = None, - empty_dir: Optional[Any] = None, + azure_file: Optional["_models.AzureFileVolume"] = None, + empty_dir: Optional[JSON] = None, secret: Optional[Dict[str, str]] = None, - git_repo: Optional["GitRepoVolume"] = None, + git_repo: Optional["_models.GitRepoVolume"] = None, **kwargs ): """ - :keyword name: Required. The name of the volume. + :keyword name: The name of the volume. Required. :paramtype name: str :keyword azure_file: The Azure File volume. :paramtype azure_file: ~azure.mgmt.containerinstance.models.AzureFileVolume :keyword empty_dir: The empty directory volume. - :paramtype empty_dir: any + :paramtype empty_dir: JSON :keyword secret: The secret volume. :paramtype secret: dict[str, str] :keyword git_repo: The git repo volume. :paramtype git_repo: ~azure.mgmt.containerinstance.models.GitRepoVolume """ - super(Volume, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.azure_file = azure_file self.empty_dir = empty_dir @@ -2372,49 +2407,42 @@ def __init__( self.git_repo = git_repo -class VolumeMount(msrest.serialization.Model): +class VolumeMount(_serialization.Model): """The properties of the volume mount. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the volume mount. + :ivar name: The name of the volume mount. Required. :vartype name: str - :ivar mount_path: Required. The path within the container where the volume should be mounted. - Must not contain colon (:). + :ivar mount_path: The path within the container where the volume should be mounted. Must not + contain colon (:). Required. :vartype mount_path: str :ivar read_only: The flag indicating whether the volume mount is read-only. :vartype read_only: bool """ _validation = { - 'name': {'required': True}, - 'mount_path': {'required': True}, + "name": {"required": True}, + "mount_path": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'mount_path': {'key': 'mountPath', 'type': 'str'}, - 'read_only': {'key': 'readOnly', 'type': 'bool'}, + "name": {"key": "name", "type": "str"}, + "mount_path": {"key": "mountPath", "type": "str"}, + "read_only": {"key": "readOnly", "type": "bool"}, } - def __init__( - self, - *, - name: str, - mount_path: str, - read_only: Optional[bool] = None, - **kwargs - ): + def __init__(self, *, name: str, mount_path: str, read_only: Optional[bool] = None, **kwargs): """ - :keyword name: Required. The name of the volume mount. + :keyword name: The name of the volume mount. Required. :paramtype name: str - :keyword mount_path: Required. The path within the container where the volume should be - mounted. Must not contain colon (:). + :keyword mount_path: The path within the container where the volume should be mounted. Must not + contain colon (:). Required. :paramtype mount_path: str :keyword read_only: The flag indicating whether the volume mount is read-only. :paramtype read_only: bool """ - super(VolumeMount, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.mount_path = mount_path self.read_only = read_only diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_patch.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/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/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/__init__.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/__init__.py index 65bb6fbdb75f..dcde5cd3ada4 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/__init__.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/__init__.py @@ -10,10 +10,18 @@ from ._operations import Operations from ._location_operations import LocationOperations from ._containers_operations import ContainersOperations +from ._subnet_service_association_link_operations import SubnetServiceAssociationLinkOperations + +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__ = [ - 'ContainerGroupsOperations', - 'Operations', - 'LocationOperations', - 'ContainersOperations', + "ContainerGroupsOperations", + "Operations", + "LocationOperations", + "ContainersOperations", + "SubnetServiceAssociationLinkOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_container_groups_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_container_groups_operations.py index f49b874b283f..95274c18ab4f 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_container_groups_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_container_groups_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,418 +6,366 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +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: - api_version = "2021-10-01" - accept = "application/json" + +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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups') + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups" + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", 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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + resource_group_name: str, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _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, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-10-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-10-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + _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_delete_request( + resource_group_name: str, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_restart_request_initial( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_restart_request( + resource_group_name: str, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_stop_request( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + resource_group_name: str, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/stop') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/stop", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_start_request_initial( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_start_request( + resource_group_name: str, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_get_outbound_network_dependencies_endpoints_request( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + resource_group_name: str, container_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/outboundNetworkDependenciesEndpoints') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/outboundNetworkDependenciesEndpoints", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class ContainerGroupsOperations(object): - """ContainerGroupsOperations 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.containerinstance.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. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ContainerGroupsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.containerinstance.ContainerInstanceManagementClient`'s + :attr:`container_groups` 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, - **kwargs: Any - ) -> Iterable["_models.ContainerGroupListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.ContainerGroup"]: """Get a list of container groups in the specified subscription. Get a list of container groups in the specified subscription. This operation returns properties @@ -424,35 +373,40 @@ def list( address type, OS type, state, and volumes. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ContainerGroupListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.ContainerGroupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ContainerGroup or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroupListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroupListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + 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, - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -466,7 +420,9 @@ 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]: @@ -475,58 +431,56 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.ContainerGroupListResult"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.ContainerGroup"]: """Get a list of container groups in the specified subscription and resource group. Get a list of container groups in a specified subscription and resource group. This operation returns properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes. - :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 ContainerGroupListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.ContainerGroupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ContainerGroup or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroupListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroupListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -540,7 +494,9 @@ 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]: @@ -549,96 +505,111 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> "_models.ContainerGroup": + def get(self, resource_group_name: str, container_group_name: str, **kwargs: Any) -> _models.ContainerGroup: """Get the properties of the specified container group. Gets the properties of the specified container group in the specified subscription and resource group. The operation returns the properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ContainerGroup, or the result of cls(response) + :return: ContainerGroup or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self.get.metadata['url'], + 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) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, container_group_name: str, - container_group: "_models.ContainerGroup", + container_group: Union[_models.ContainerGroup, IO], **kwargs: Any - ) -> "_models.ContainerGroup": - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(container_group, 'ContainerGroup') + ) -> _models.ContainerGroup: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(container_group, (IO, bytes)): + _content = container_group + else: + _json = self._serialize.body(container_group, "ContainerGroup") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, container_group_name=container_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -646,37 +617,42 @@ def _create_or_update_initial( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, container_group_name: str, - container_group: "_models.ContainerGroup", + container_group: _models.ContainerGroup, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.ContainerGroup"]: + ) -> LROPoller[_models.ContainerGroup]: """Create or update container groups. Create or update container groups with specified configurations. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :param container_group: The properties of the container group to be created or updated. + Required. :type container_group: ~azure.mgmt.containerinstance.models.ContainerGroup + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -688,134 +664,289 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either ContainerGroup or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + container_group_name: str, + container_group: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ContainerGroup]: + """Create or update container groups. + + Create or update container groups with specified configurations. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_group: The properties of the container group to be created or updated. + Required. + :type container_group: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ContainerGroup or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + container_group_name: str, + container_group: Union[_models.ContainerGroup, IO], + **kwargs: Any + ) -> LROPoller[_models.ContainerGroup]: + """Create or update container groups. + + Create or update container groups with specified configurations. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_group: The properties of the container group to be created or updated. Is + either a model type or a IO type. Required. + :type container_group: ~azure.mgmt.containerinstance.models.ContainerGroup or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ContainerGroup or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_initial( + raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, container_group=container_group, + api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore - @distributed_trace + @overload def update( self, resource_group_name: str, container_group_name: str, - resource: "_models.Resource", + resource: _models.Resource, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ContainerGroup": + ) -> _models.ContainerGroup: """Update container groups. Updates container group tags with specified values. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param resource: The container group resource with just the tags to be updated. + :param resource: The container group resource with just the tags to be updated. Required. :type resource: ~azure.mgmt.containerinstance.models.Resource + :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: ContainerGroup or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + container_group_name: str, + resource: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ContainerGroup: + """Update container groups. + + Updates container group tags with specified values. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param resource: The container group resource with just the tags to be updated. Required. + :type resource: 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: ContainerGroup, or the result of cls(response) + :return: ContainerGroup or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + @distributed_trace + def update( + self, resource_group_name: str, container_group_name: str, resource: Union[_models.Resource, IO], **kwargs: Any + ) -> _models.ContainerGroup: + """Update container groups. - _json = self._serialize.body(resource, 'Resource') + Updates container group tags with specified values. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param resource: The container group resource with just the tags to be updated. Is either a + model type or a IO type. Required. + :type resource: ~azure.mgmt.containerinstance.models.Resource 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: ContainerGroup or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IO, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "Resource") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore def _delete_initial( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> Optional["_models.ContainerGroup"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ContainerGroup"]] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + self, resource_group_name: str, container_group_name: str, **kwargs: Any + ) -> Optional[_models.ContainerGroup]: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ContainerGroup]] + + request = build_delete_request( resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -824,31 +955,27 @@ def _delete_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore @distributed_trace def begin_delete( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> LROPoller["_models.ContainerGroup"]: + self, resource_group_name: str, container_group_name: str, **kwargs: Any + ) -> LROPoller[_models.ContainerGroup]: """Delete the specified container group. Delete the specified container group in the specified subscription and resource group. The operation does not delete other resources provided by the user, such as volumes. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -861,70 +988,79 @@ def begin_delete( :return: An instance of LROPoller that returns either ContainerGroup or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerGroup] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('ContainerGroup', pipeline_response) + deserialized = self._deserialize("ContainerGroup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}"} # type: ignore - def _restart_initial( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + def _restart_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_restart_request( resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self._restart_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._restart_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: @@ -934,24 +1070,18 @@ def _restart_initial( if cls: return cls(pipeline_response, None, {}) - _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart'} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart"} # type: ignore @distributed_trace - def begin_restart( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_restart(self, resource_group_name: str, container_group_name: str, **kwargs: Any) -> LROPoller[None]: """Restarts all containers in a container group. Restarts all containers in a container group in place. If container image has updates, new image will be downloaded. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -963,82 +1093,92 @@ def begin_restart( Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._restart_initial( + raw_result = self._restart_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart'} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart"} # type: ignore @distributed_trace - def stop( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + def stop( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: """Stops all containers in a container group. Stops all containers in a container group. Compute resources will be deallocated and billing will stop. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_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', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_stop_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self.stop.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.stop.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1048,59 +1188,57 @@ def stop( if cls: return cls(pipeline_response, None, {}) - stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/stop'} # type: ignore + stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/stop"} # type: ignore - - def _start_initial( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + def _start_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_start_request( resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self._start_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._start_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response - if response.status_code not in [202]: + if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start'} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start"} # type: ignore @distributed_trace - def begin_start( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_start(self, resource_group_name: str, container_group_name: str, **kwargs: Any) -> LROPoller[None]: """Starts all containers in a container group. Starts all containers in a container group. Compute resources will be allocated and billing will start. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -1112,94 +1250,103 @@ def begin_start( Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._start_initial( + raw_result = self._start_initial( # type: ignore resource_group_name=resource_group_name, container_group_name=container_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start'} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start"} # type: ignore @distributed_trace def get_outbound_network_dependencies_endpoints( - self, - resource_group_name: str, - container_group_name: str, - **kwargs: Any + self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> List[str]: """Get all network dependencies for container group. Gets all the network dependencies for this container group to allow complete control of network setting and configuration. For container groups, this will always be an empty list. - :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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: list of str, or the result of cls(response) + :return: list of str or the result of cls(response) :rtype: list[str] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[List[str]] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[List[str]] - request = build_get_outbound_network_dependencies_endpoints_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, - template_url=self.get_outbound_network_dependencies_endpoints.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_outbound_network_dependencies_endpoints.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('[str]', pipeline_response) + deserialized = self._deserialize("[str]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_outbound_network_dependencies_endpoints.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/outboundNetworkDependenciesEndpoints'} # type: ignore - + get_outbound_network_dependencies_endpoints.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/outboundNetworkDependenciesEndpoints"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_containers_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_containers_operations.py index e8d82a4fe7ab..747e6f308dc3 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_containers_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_containers_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,174 +6,161 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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.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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_logs_request( - subscription_id: str, resource_group_name: str, container_group_name: str, container_name: str, + subscription_id: str, *, tail: Optional[int] = None, timestamps: Optional[bool] = None, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), - "containerName": _SERIALIZER.url("container_name", container_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if tail is not None: - query_parameters['tail'] = _SERIALIZER.query("tail", tail, 'int') + _params["tail"] = _SERIALIZER.query("tail", tail, "int") if timestamps is not None: - query_parameters['timestamps'] = _SERIALIZER.query("timestamps", timestamps, 'bool') + _params["timestamps"] = _SERIALIZER.query("timestamps", timestamps, "bool") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_execute_command_request( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - container_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, container_group_name: str, container_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _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", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2021-10-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/exec') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/exec", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), - "containerName": _SERIALIZER.url("container_name", container_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_attach_request( - subscription_id: str, - resource_group_name: str, - container_group_name: str, - container_name: str, - **kwargs: Any + resource_group_name: str, container_group_name: str, container_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/attach') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/attach", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, 'str'), - "containerName": _SERIALIZER.url("container_name", container_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "containerGroupName": _SERIALIZER.url("container_group_name", container_group_name, "str"), + "containerName": _SERIALIZER.url("container_name", container_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class ContainersOperations(object): - """ContainersOperations 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.containerinstance.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. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ContainersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.containerinstance.ContainerInstanceManagementClient`'s + :attr:`containers` 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_logs( @@ -183,64 +171,137 @@ def list_logs( tail: Optional[int] = None, timestamps: Optional[bool] = None, **kwargs: Any - ) -> "_models.Logs": + ) -> _models.Logs: """Get the logs for a specified container instance. Get the logs for a specified container instance in a specified resource group and container 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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param container_name: The name of the container instance. + :param container_name: The name of the container instance. Required. :type container_name: str :param tail: The number of lines to show from the tail of the container instance log. If not - provided, all available logs are shown up to 4mb. + provided, all available logs are shown up to 4mb. Default value is None. :type tail: int :param timestamps: If true, adds a timestamp at the beginning of every line of log output. If - not provided, defaults to false. + not provided, defaults to false. Default value is None. :type timestamps: bool :keyword callable cls: A custom type or function that will be passed the direct response - :return: Logs, or the result of cls(response) + :return: Logs or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.Logs - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Logs"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Logs] - request = build_list_logs_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, container_name=container_name, + subscription_id=self._config.subscription_id, tail=tail, timestamps=timestamps, - template_url=self.list_logs.metadata['url'], + api_version=api_version, + template_url=self.list_logs.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Logs', pipeline_response) + deserialized = self._deserialize("Logs", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_logs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs'} # type: ignore + list_logs.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs"} # type: ignore + + @overload + def execute_command( + self, + resource_group_name: str, + container_group_name: str, + container_name: str, + container_exec_request: _models.ContainerExecRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ContainerExecResponse: + """Executes a command in a specific container instance. + Executes a command for a specific container instance in a specified resource group and + container group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_name: The name of the container instance. Required. + :type container_name: str + :param container_exec_request: The request for the exec command. Required. + :type container_exec_request: ~azure.mgmt.containerinstance.models.ContainerExecRequest + :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: ContainerExecResponse or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerExecResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def execute_command( + self, + resource_group_name: str, + container_group_name: str, + container_name: str, + container_exec_request: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ContainerExecResponse: + """Executes a command in a specific container instance. + + Executes a command for a specific container instance in a specified resource group and + container group. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param container_group_name: The name of the container group. Required. + :type container_group_name: str + :param container_name: The name of the container instance. Required. + :type container_name: str + :param container_exec_request: The request for the exec command. Required. + :type container_exec_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ContainerExecResponse or the result of cls(response) + :rtype: ~azure.mgmt.containerinstance.models.ContainerExecResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def execute_command( @@ -248,120 +309,141 @@ def execute_command( resource_group_name: str, container_group_name: str, container_name: str, - container_exec_request: "_models.ContainerExecRequest", + container_exec_request: Union[_models.ContainerExecRequest, IO], **kwargs: Any - ) -> "_models.ContainerExecResponse": + ) -> _models.ContainerExecResponse: """Executes a command in a specific container instance. Executes a command for a specific container instance in a specified resource group and container 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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param container_name: The name of the container instance. + :param container_name: The name of the container instance. Required. :type container_name: str - :param container_exec_request: The request for the exec command. - :type container_exec_request: ~azure.mgmt.containerinstance.models.ContainerExecRequest + :param container_exec_request: The request for the exec command. Is either a model type or a IO + type. Required. + :type container_exec_request: ~azure.mgmt.containerinstance.models.ContainerExecRequest 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: ContainerExecResponse, or the result of cls(response) + :return: ContainerExecResponse or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerExecResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerExecResponse"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(container_exec_request, 'ContainerExecRequest') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerExecResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(container_exec_request, (IO, bytes)): + _content = container_exec_request + else: + _json = self._serialize.body(container_exec_request, "ContainerExecRequest") request = build_execute_command_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, container_name=container_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute_command.metadata['url'], + content=_content, + template_url=self.execute_command.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerExecResponse', pipeline_response) + deserialized = self._deserialize("ContainerExecResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute_command.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/exec'} # type: ignore - + execute_command.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/exec"} # type: ignore @distributed_trace def attach( - self, - resource_group_name: str, - container_group_name: str, - container_name: str, - **kwargs: Any - ) -> "_models.ContainerAttachResponse": + self, resource_group_name: str, container_group_name: str, container_name: str, **kwargs: Any + ) -> _models.ContainerAttachResponse: """Attach to the output of a specific container instance. Attach to the output stream of a specific container instance in a specified resource group and container 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 container_group_name: The name of the container group. + :param container_group_name: The name of the container group. Required. :type container_group_name: str - :param container_name: The name of the container instance. + :param container_name: The name of the container instance. Required. :type container_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ContainerAttachResponse, or the result of cls(response) + :return: ContainerAttachResponse or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerAttachResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerAttachResponse"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ContainerAttachResponse] - request = build_attach_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, container_group_name=container_group_name, container_name=container_name, - template_url=self.attach.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.attach.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ContainerAttachResponse', pipeline_response) + deserialized = self._deserialize("ContainerAttachResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - attach.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/attach'} # type: ignore - + attach.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/attach"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_location_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_location_operations.py index 0da0918bb360..b9585fe2c500 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_location_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_location_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,187 +6,180 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_usage_request( - subscription_id: str, - location: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + +def build_list_usage_request(location: 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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/usages') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/usages", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_list_cached_images_request( - subscription_id: str, - location: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_cached_images_request(location: 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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/cachedImages') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/cachedImages", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_list_capabilities_request( - subscription_id: str, - location: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_capabilities_request(location: 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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/capabilities') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/capabilities", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class LocationOperations(object): - """LocationOperations 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.containerinstance.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. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class LocationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.containerinstance.ContainerInstanceManagementClient`'s + :attr:`location` 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_usage( - self, - location: str, - **kwargs: Any - ) -> Iterable["_models.UsageListResult"]: + def list_usage(self, location: str, **kwargs: Any) -> Iterable["_models.Usage"]: """Get the usage for a subscription. - :param location: The identifier for the physical azure location. + :param location: The identifier for the physical azure location. Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either UsageListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.UsageListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Usage or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.Usage] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.UsageListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.UsageListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_usage_request( - subscription_id=self._config.subscription_id, location=location, - template_url=self.list_usage.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_usage.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_usage_request( - subscription_id=self._config.subscription_id, - location=location, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -199,7 +193,9 @@ 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]: @@ -208,56 +204,54 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_usage.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/usages'} # type: ignore + list_usage.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/usages"} # type: ignore @distributed_trace - def list_cached_images( - self, - location: str, - **kwargs: Any - ) -> Iterable["_models.CachedImagesListResult"]: + def list_cached_images(self, location: str, **kwargs: Any) -> Iterable["_models.CachedImages"]: """Get the list of cached images. Get the list of cached images on specific OS type for a subscription in a region. - :param location: The identifier for the physical azure location. + :param location: The identifier for the physical azure location. Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CachedImagesListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.CachedImagesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CachedImages or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.CachedImages] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CachedImagesListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CachedImagesListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_cached_images_request( - subscription_id=self._config.subscription_id, location=location, - template_url=self.list_cached_images.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_cached_images.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_cached_images_request( - subscription_id=self._config.subscription_id, - location=location, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -271,7 +265,9 @@ 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]: @@ -280,56 +276,54 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_cached_images.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/cachedImages'} # type: ignore + list_cached_images.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/cachedImages"} # type: ignore @distributed_trace - def list_capabilities( - self, - location: str, - **kwargs: Any - ) -> Iterable["_models.CapabilitiesListResult"]: + def list_capabilities(self, location: str, **kwargs: Any) -> Iterable["_models.Capabilities"]: """Get the list of capabilities of the location. Get the list of CPU/memory/GPU capabilities of a region. - :param location: The identifier for the physical azure location. + :param location: The identifier for the physical azure location. Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CapabilitiesListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.CapabilitiesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Capabilities or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.containerinstance.models.Capabilities] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CapabilitiesListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CapabilitiesListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_capabilities_request( - subscription_id=self._config.subscription_id, location=location, - template_url=self.list_capabilities.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_capabilities.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_capabilities_request( - subscription_id=self._config.subscription_id, - location=location, - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -343,7 +337,9 @@ 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]: @@ -352,8 +348,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_capabilities.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/capabilities'} # type: ignore + list_capabilities.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/capabilities"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_operations.py index 77293a8b6622..e2c8debf9164 100644 --- a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_operations.py +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,106 +6,111 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = "2021-10-01" - accept = "application/json" + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/providers/Microsoft.ContainerInstance/operations') + _url = kwargs.pop("template_url", "/providers/Microsoft.ContainerInstance/operations") # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class Operations(object): - """Operations operations. - - 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.containerinstance.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. + _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.containerinstance.ContainerInstanceManagementClient`'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 __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.OperationListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """List the operations for Azure Container Instance service. :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.containerinstance.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.containerinstance.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - template_url=self.list.metadata['url'], + 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) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - template_url=next_link, - ) + # make call to next link with the client's api-version + _parsed_next_link = urlparse(next_link) + _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -118,7 +124,9 @@ 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]: @@ -127,8 +135,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.ContainerInstance/operations'} # type: ignore + list.metadata = {"url": "/providers/Microsoft.ContainerInstance/operations"} # type: ignore diff --git a/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_patch.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/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/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_subnet_service_association_link_operations.py b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_subnet_service_association_link_operations.py new file mode 100644 index 000000000000..015c995be490 --- /dev/null +++ b/sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/operations/_subnet_service_association_link_operations.py @@ -0,0 +1,196 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_delete_request( + resource_group_name: str, virtual_network_name: str, subnet_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", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/providers/Microsoft.ContainerInstance/serviceAssociationLinks/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "virtualNetworkName": _SERIALIZER.url("virtual_network_name", virtual_network_name, "str"), + "subnetName": _SERIALIZER.url("subnet_name", subnet_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class SubnetServiceAssociationLinkOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.containerinstance.ContainerInstanceManagementClient`'s + :attr:`subnet_service_association_link` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, virtual_network_name: str, subnet_name: str, **kwargs: Any + ) -> None: + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + virtual_network_name=virtual_network_name, + subnet_name=subnet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/providers/Microsoft.ContainerInstance/serviceAssociationLinks/default"} # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, virtual_network_name: str, subnet_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Delete container group virtual network association links. + + Delete container group virtual network association links. The operation does not delete other + resources provided by the user. + + :param resource_group_name: The name of the resource group. Required. + :type resource_group_name: str + :param virtual_network_name: The name of the virtual network. Required. + :type virtual_network_name: str + :param subnet_name: The name of the subnet. Required. + :type subnet_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + virtual_network_name=virtual_network_name, + subnet_name=subnet_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/providers/Microsoft.ContainerInstance/serviceAssociationLinks/default"} # type: ignore