diff --git a/.vscode/cspell.json b/.vscode/cspell.json index de43ddb8ebcb..04b7bff66bb5 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -1106,6 +1106,16 @@ "mrenclave", "infile" ] + }, + { + "filename": "sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/*.py", + "words": [ + "Nify", + "ctxt", + "unflattened", + "deseralize", + "wday" + ] } ], "allowCompoundWords": true diff --git a/eng/tox/allowed_pylint_failures.py b/eng/tox/allowed_pylint_failures.py index e934eaa4a02c..364959bd0e7f 100644 --- a/eng/tox/allowed_pylint_failures.py +++ b/eng/tox/allowed_pylint_failures.py @@ -58,5 +58,6 @@ "azure-purview-administration", "azure-messaging-nspkg", "azure-agrifood-farming", - "azure-developer-loadtesting" + "azure-developer-loadtesting", + "azure-developer-devcenter" ] diff --git a/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md new file mode 100644 index 000000000000..7fbc3a6f6db6 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 1.0.0b1 (2022-11-01) + +- Initial version for the DevCenter service diff --git a/sdk/devcenter/azure-developer-devcenter/LICENSE b/sdk/devcenter/azure-developer-devcenter/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/MANIFEST.in b/sdk/devcenter/azure-developer-devcenter/MANIFEST.in new file mode 100644 index 000000000000..2ff00927e078 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/MANIFEST.in @@ -0,0 +1,7 @@ +include *.md +include LICENSE +include azure/developer/devcenter/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/developer/__init__.py \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/README.md b/sdk/devcenter/azure-developer-devcenter/README.md new file mode 100644 index 000000000000..b11fa0fbb45d --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/README.md @@ -0,0 +1,156 @@ + +# Azure DevCenter Service client library for Python +The Azure DevCenter package provides access to manage resources for Microsoft Dev Box and Azure Deployment Environments. This SDK enables managing developer machines and environments in Azure. + +Use the package for Azure DevCenter to: +> Create, access, manage, and delete Dev Box resources +> Create, deploy, manage, and delete Environment resources + +## Getting started + +### Installating the package + +```bash +python -m pip install azure-developer-devcenter +``` + +#### Prequisites + +- Python 3.7 or later is required to use this package. +- You need an [Azure subscription][azure_sub] to use this package. +- You must have [configured](https://learn.microsoft.com/azure/dev-box/quickstart-configure-dev-box-service) a DevCenter, Project, Network Connection, Dev Box Definition, and Pool before you can create Dev Boxes +- You must have [configured](https://learn.microsoft.com/azure/deployment-environments/) a DevCenter, Project, Catalog, and Environment Type before you can create Environments + +#### Create with an Azure Active Directory Credential +To use an [Azure Active Directory (AAD) token credential][authenticate_with_token], +provide an instance of the desired credential type obtained from the +[azure-identity][azure_identity_credentials] library. + +To authenticate with AAD, you must first [pip][pip] install [`azure-identity`][azure_identity_pip] + +After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use. +As an example, [DefaultAzureCredential][default_azure_credential] can be used to authenticate the client: + +Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: +`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET` + +Use the returned token credential to authenticate the client: + +```python +>>> import os +>>> from azure.developer.devcenter import DevCenterClient +>>> from azure.identity import DefaultAzureCredential +>>> tenant_id = os.environ['AZURE_TENANT_ID'] +>>> client = DevCenterClient(tenant_id=tenant_id, dev_center="my_dev_center", credential=DefaultAzureCredential()) +``` + +## Examples + +### Dev Box Management +```python +>>> import os +>>> from azure.developer.devcenter import DevCenterClient +>>> from azure.identity import DefaultAzureCredential +>>> from azure.core.exceptions import HttpResponseError +>>> tenant_id = os.environ['AZURE_TENANT_ID'] +>>> client = DevCenterClient(tenant_id=tenant_id, dev_center="my_dev_center", credential=DefaultAzureCredential()) +>>> try: + # Fetch control plane resource dependencies + projects = list(client.dev_center.list_projects(top=1)) + target_project_name = projects[0]['name'] + + pools = list(client.dev_boxes.list_pools(target_project_name, top=1)) + target_pool_name = pools[0]['name'] + + # Stand up a new dev box + create_response = client.dev_boxes.begin_create_dev_box(target_project_name, "Test_DevBox", {"poolName": target_pool_name}) + devbox_result = create_response.result() + + LOG.info(f"Provisioned dev box with status {devbox_result['provisioningState']}.") + + # Connect to the provisioned dev box + remote_connection_response = client.dev_boxes.get_remote_connection(target_project_name, "Test_DevBox") + LOG.info(f"Connect to the dev box using web URL {remote_connection_response['webUrl']}") + + # Tear down the dev box when finished + delete_response = client.dev_boxes.begin_delete_dev_box(target_project_name, "Test_DevBox") + delete_response.wait() + LOG.info("Deleted dev box successfully.") + except HttpResponseError as e: + print('service responds error: {}'.format(e.response.json())) + +``` + +### Environment Management +```python +>>> import os +>>> from azure.developer.devcenter import DevCenterClient +>>> from azure.identity import DefaultAzureCredential +>>> from azure.core.exceptions import HttpResponseError +>>> tenant_id = os.environ['AZURE_TENANT_ID'] +>>> client = DevCenterClient(tenant_id=tenant_id, dev_center="my_dev_center", credential=DefaultAzureCredential()) +>>> try: + # Fetch control plane resource dependencies + target_project_name = list(client.dev_center.list_projects(top=1))[0]['name'] + target_catalog_item_name = list(client.environments.list_catalog_items(target_project_name, top=1))[0]['name'] + target_environment_type_name = list(client.environments.list_environment_types(target_project_name, top=1))[0]['name'] + + # Stand up a new environment + create_response = client.environments.begin_create_environment(target_project_name, + "Dev_Environment", + {"catalogItemName": target_catalog_item_name, "environmentType": target_environment_type_name}) + environment_result = create_response.result() + + LOG.info(f"Provisioned environment with status {environment_result['provisioningState']}.") + + # Fetch deployment artifacts + artifact_response = client.environments.list_artifacts_by_environment(target_project_name, "Dev_Environment") + + for artifact in artifact_response: + LOG.info(artifact) + + # Tear down the environment when finished + delete_response = client.environments.begin_delete_environment(target_project_name, "Dev_Environment") + delete_response.wait() + LOG.info("Completed deletion for the environment.") + except HttpResponseError as e: + print('service responds error: {}'.format(e.response.json())) + +``` +## Key concepts +Dev Boxes refer to managed developer machines running in Azure. Dev Boxes are provisioned in Pools, which define the network and image used for a Dev Box. + +Environments refer to templated developer environments, which combine a template (Catalog Item) and parameters. + +## Troubleshooting +Errors can occur during initial requests and long-running operations, and will provide information about how to resolve the error. +Be sure to confirm that dependent resources, such as pools and catalogs, are set up properly and are in a healthy state. You will not be able to create resources with the package when your dependent resources are in a failed state. + +## Next steps +Get started by exploring our samples and starting to use the package! + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct][code_of_conduct]. For more information, +see the Code of Conduct FAQ or contact opencode@microsoft.com with any +additional questions or comments. + + +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ +[authenticate_with_token]: https://docs.microsoft.com/azure/cognitive-services/authentication?tabs=powershell#authenticate-with-an-authentication-token +[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials +[azure_identity_pip]: https://pypi.org/project/azure-identity/ +[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential +[pip]: https://pypi.org/project/pip/ +[azure_sub]: https://azure.microsoft.com/free/ diff --git a/sdk/devcenter/azure-developer-devcenter/azure/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/__init__.py new file mode 100644 index 000000000000..7abeeb9de152 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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 ._client import DevCenterClient +from ._version import VERSION + +__version__ = VERSION + +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__ = ["DevCenterClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py new file mode 100644 index 000000000000..3f8053135758 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_client.py @@ -0,0 +1,119 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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 copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core import PipelineClient +from azure.core.rest import HttpRequest, HttpResponse + +from ._configuration import DevCenterClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import DevBoxesOperations, DevCenterOperations, EnvironmentsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Dict + + from azure.core.credentials import TokenCredential + + +class DevCenterClient: # pylint: disable=client-accepts-api-version-keyword + """DevBox API. + + :ivar dev_center: DevCenterOperations operations + :vartype dev_center: azure.developer.devcenter.operations.DevCenterOperations + :ivar dev_boxes: DevBoxesOperations operations + :vartype dev_boxes: azure.developer.devcenter.operations.DevBoxesOperations + :ivar environments: EnvironmentsOperations operations + :vartype environments: azure.developer.devcenter.operations.EnvironmentsOperations + :param tenant_id: The tenant to operate on. Required. + :type tenant_id: str + :param dev_center: The DevCenter to operate on. Required. + :type dev_center: str + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param dev_center_dns_suffix: The DNS suffix used as the base for all devcenter requests. + Default value is "devcenter.azure.com". + :type dev_center_dns_suffix: str + :keyword api_version: Api Version. Default value is "2022-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + tenant_id: str, + dev_center: str, + credential: "TokenCredential", + dev_center_dns_suffix: str = "devcenter.azure.com", + **kwargs: Any + ) -> None: + _endpoint = "https://{tenantId}-{devCenter}.{devCenterDnsSuffix}" + self._config = DevCenterClientConfiguration( + tenant_id=tenant_id, + dev_center=dev_center, + credential=credential, + dev_center_dns_suffix=dev_center_dns_suffix, + **kwargs + ) + self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.dev_center = DevCenterOperations(self._client, self._config, self._serialize, self._deserialize) + self.dev_boxes = DevBoxesOperations(self._client, self._config, self._serialize, self._deserialize) + self.environments = EnvironmentsOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> DevCenterClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py new file mode 100644 index 000000000000..4e83edb18b04 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_configuration.py @@ -0,0 +1,86 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class DevCenterClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for DevCenterClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param tenant_id: The tenant to operate on. Required. + :type tenant_id: str + :param dev_center: The DevCenter to operate on. Required. + :type dev_center: str + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param dev_center_dns_suffix: The DNS suffix used as the base for all devcenter requests. + Default value is "devcenter.azure.com". + :type dev_center_dns_suffix: str + :keyword api_version: Api Version. Default value is "2022-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + tenant_id: str, + dev_center: str, + credential: "TokenCredential", + dev_center_dns_suffix: str = "devcenter.azure.com", + **kwargs: Any + ) -> None: + super(DevCenterClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-03-01-preview") # type: str + + if tenant_id is None: + raise ValueError("Parameter 'tenant_id' must not be None.") + if dev_center is None: + raise ValueError("Parameter 'dev_center' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if dev_center_dns_suffix is None: + raise ValueError("Parameter 'dev_center_dns_suffix' must not be None.") + + self.tenant_id = tenant_id + self.dev_center = dev_center + self.credential = credential + self.dev_center_dns_suffix = dev_center_dns_suffix + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://devcenter.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "developer-devcenter/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure( + 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 policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_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/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py new file mode 100644 index 000000000000..54f238858ed8 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_vendor.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/__init__.py new file mode 100644 index 000000000000..195eb86633a1 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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 ._client import DevCenterClient + +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__ = ["DevCenterClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_client.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_client.py new file mode 100644 index 000000000000..bae63f25ebf1 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_client.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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 copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core import AsyncPipelineClient +from azure.core.rest import AsyncHttpResponse, HttpRequest + +from .._serialization import Deserializer, Serializer +from ._configuration import DevCenterClientConfiguration +from .operations import DevBoxesOperations, DevCenterOperations, EnvironmentsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Dict + + from azure.core.credentials_async import AsyncTokenCredential + + +class DevCenterClient: # pylint: disable=client-accepts-api-version-keyword + """DevBox API. + + :ivar dev_center: DevCenterOperations operations + :vartype dev_center: azure.developer.devcenter.aio.operations.DevCenterOperations + :ivar dev_boxes: DevBoxesOperations operations + :vartype dev_boxes: azure.developer.devcenter.aio.operations.DevBoxesOperations + :ivar environments: EnvironmentsOperations operations + :vartype environments: azure.developer.devcenter.aio.operations.EnvironmentsOperations + :param tenant_id: The tenant to operate on. Required. + :type tenant_id: str + :param dev_center: The DevCenter to operate on. Required. + :type dev_center: str + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param dev_center_dns_suffix: The DNS suffix used as the base for all devcenter requests. + Default value is "devcenter.azure.com". + :type dev_center_dns_suffix: str + :keyword api_version: Api Version. Default value is "2022-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + tenant_id: str, + dev_center: str, + credential: "AsyncTokenCredential", + dev_center_dns_suffix: str = "devcenter.azure.com", + **kwargs: Any + ) -> None: + _endpoint = "https://{tenantId}-{devCenter}.{devCenterDnsSuffix}" + self._config = DevCenterClientConfiguration( + tenant_id=tenant_id, + dev_center=dev_center, + credential=credential, + dev_center_dns_suffix=dev_center_dns_suffix, + **kwargs + ) + self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.dev_center = DevCenterOperations(self._client, self._config, self._serialize, self._deserialize) + self.dev_boxes = DevBoxesOperations(self._client, self._config, self._serialize, self._deserialize) + self.environments = EnvironmentsOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "DevCenterClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_configuration.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_configuration.py new file mode 100644 index 000000000000..f44f3e3314da --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_configuration.py @@ -0,0 +1,83 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class DevCenterClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for DevCenterClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param tenant_id: The tenant to operate on. Required. + :type tenant_id: str + :param dev_center: The DevCenter to operate on. Required. + :type dev_center: str + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param dev_center_dns_suffix: The DNS suffix used as the base for all devcenter requests. + Default value is "devcenter.azure.com". + :type dev_center_dns_suffix: str + :keyword api_version: Api Version. Default value is "2022-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + tenant_id: str, + dev_center: str, + credential: "AsyncTokenCredential", + dev_center_dns_suffix: str = "devcenter.azure.com", + **kwargs: Any + ) -> None: + super(DevCenterClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-03-01-preview") # type: str + + if tenant_id is None: + raise ValueError("Parameter 'tenant_id' must not be None.") + if dev_center is None: + raise ValueError("Parameter 'dev_center' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if dev_center_dns_suffix is None: + raise ValueError("Parameter 'dev_center_dns_suffix' must not be None.") + + self.tenant_id = tenant_id + self.dev_center = dev_center + self.credential = credential + self.dev_center_dns_suffix = dev_center_dns_suffix + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://devcenter.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "developer-devcenter/{}".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 policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/__init__.py new file mode 100644 index 000000000000..7350c68142b7 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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 ._operations import DevCenterOperations +from ._operations import DevBoxesOperations +from ._operations import EnvironmentsOperations + +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__ = [ + "DevCenterOperations", + "DevBoxesOperations", + "EnvironmentsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/_operations.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/_operations.py new file mode 100644 index 000000000000..6db47df0b121 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/_operations.py @@ -0,0 +1,5199 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, 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, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.polling.async_base_polling import AsyncLROBasePolling +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 ...operations._operations import ( + build_dev_boxes_create_dev_box_request, + build_dev_boxes_delete_dev_box_request, + build_dev_boxes_get_dev_box_by_user_request, + build_dev_boxes_get_pool_request, + build_dev_boxes_get_remote_connection_request, + build_dev_boxes_get_schedule_by_pool_request, + build_dev_boxes_list_dev_boxes_by_user_request, + build_dev_boxes_list_pools_request, + build_dev_boxes_list_schedules_by_pool_request, + build_dev_boxes_start_dev_box_request, + build_dev_boxes_stop_dev_box_request, + build_dev_center_get_project_request, + build_dev_center_list_all_dev_boxes_by_user_request, + build_dev_center_list_all_dev_boxes_request, + build_dev_center_list_projects_request, + build_environments_create_or_update_environment_request, + build_environments_custom_environment_action_request, + build_environments_delete_environment_action_request, + build_environments_delete_environment_request, + build_environments_deploy_environment_action_request, + build_environments_get_catalog_item_request, + build_environments_get_catalog_item_version_request, + build_environments_get_environment_by_user_request, + build_environments_list_artifacts_by_environment_and_path_request, + build_environments_list_artifacts_by_environment_request, + build_environments_list_catalog_item_versions_request, + build_environments_list_catalog_items_request, + build_environments_list_environment_types_request, + build_environments_list_environments_by_user_request, + build_environments_list_environments_request, + build_environments_update_environment_request, +) + +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 +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DevCenterOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.developer.devcenter.aio.DevCenterClient`'s + :attr:`dev_center` attribute. + """ + + 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_projects( + self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists all projects. + + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "description": "str", # Optional. Description of the project. + "name": "str" # Optional. Name of the project. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_center_list_projects_request( + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_project(self, project_name: str, **kwargs: Any) -> JSON: + """Gets a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "description": "str", # Optional. Description of the project. + "name": "str" # Optional. Name of the project. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_center_get_project_request( + project_name=project_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_all_dev_boxes( + self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists Dev Boxes that the caller has access to in the DevCenter. + + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_center_list_all_dev_boxes_request( + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_all_dev_boxes_by_user( + self, user_id: str = "me", *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists Dev Boxes in the Dev Center for a particular user. + + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_center_list_all_dev_boxes_by_user_request( + user_id=user_id, + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class DevBoxesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.developer.devcenter.aio.DevCenterClient`'s + :attr:`dev_boxes` attribute. + """ + + 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_pools( + self, project_name: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists available pools. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether owners of Dev + Boxes in this pool are local administrators on the Dev Boxes. Known values are: + "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where Dev Boxes in the pool are + located. + "name": "str", # Optional. Pool name. + "osType": "str", # Optional. The operating system type of Dev Boxes in this + pool. "Windows" + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + } + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_boxes_list_pools_request( + project_name=project_name, + top=top, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_pool(self, pool_name: str, project_name: str, **kwargs: Any) -> JSON: + """Gets a pool. + + :param pool_name: The name of a pool of Dev Boxes. Required. + :type pool_name: str + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether owners of Dev + Boxes in this pool are local administrators on the Dev Boxes. Known values are: + "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where Dev Boxes in the pool are + located. + "name": "str", # Optional. Pool name. + "osType": "str", # Optional. The operating system type of Dev Boxes in this + pool. "Windows" + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + } + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_pool_request( + pool_name=pool_name, + project_name=project_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_schedules_by_pool( + self, + project_name: str, + pool_name: str, + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists available schedules for a pool. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param pool_name: The name of a pool of Dev Boxes. Required. + :type pool_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "frequency": "str", # Optional. The frequency of this scheduled task. + "Daily" + "name": "str", # Optional. Display name for the Schedule. + "time": "str", # Optional. The target time to trigger the action. The format + is HH:MM. + "timeZone": "str", # Optional. The IANA timezone id at which the schedule + should execute. + "type": "str" # Optional. Supported type this scheduled task represents. + "StopDevBox" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_boxes_list_schedules_by_pool_request( + project_name=project_name, + pool_name=pool_name, + top=top, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_schedule_by_pool(self, project_name: str, pool_name: str, schedule_name: str, **kwargs: Any) -> JSON: + """Gets a schedule. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param pool_name: The name of a pool of Dev Boxes. Required. + :type pool_name: str + :param schedule_name: The name of a schedule. Required. + :type schedule_name: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "frequency": "str", # Optional. The frequency of this scheduled task. + "Daily" + "name": "str", # Optional. Display name for the Schedule. + "time": "str", # Optional. The target time to trigger the action. The format + is HH:MM. + "timeZone": "str", # Optional. The IANA timezone id at which the schedule + should execute. + "type": "str" # Optional. Supported type this scheduled task represents. + "StopDevBox" + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_schedule_by_pool_request( + project_name=project_name, + pool_name=pool_name, + schedule_name=schedule_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_dev_boxes_by_user( + self, + project_name: str, + user_id: str = "me", + *, + filter: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists Dev Boxes in the project for a particular user. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_boxes_list_dev_boxes_by_user_request( + project_name=project_name, + user_id=user_id, + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_dev_box_by_user( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> JSON: + """Gets a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_dev_box_by_user_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + async def _create_dev_box_initial( + self, project_name: str, dev_box_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> JSON: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_dev_boxes_create_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 201: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @overload + async def begin_create_dev_box( + self, + project_name: str, + dev_box_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Creates or updates a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents a environment. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + + # response body for status code(s): 200, 201 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + + @overload + async def begin_create_dev_box( + self, + project_name: str, + dev_box_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Creates or updates a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents a environment. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + + @distributed_trace_async + async def begin_create_dev_box( + self, project_name: str, dev_box_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Creates or updates a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents a environment. Is either a model type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + async def _delete_dev_box_initial( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> Optional[JSON]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[JSON]] + + request = build_dev_boxes_delete_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # 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) + + deserialized = None + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace_async + async def begin_delete_dev_box( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Deletes a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **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) + + async def _start_dev_box_initial( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> Optional[JSON]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[JSON]] + + request = build_dev_boxes_start_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace_async + async def begin_start_dev_box( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Starts a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "location"}, + path_format_arguments=path_format_arguments, + **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) + + async def _stop_dev_box_initial( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> Optional[JSON]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[JSON]] + + request = build_dev_boxes_stop_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace_async + async def begin_stop_dev_box( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Stops a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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._stop_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "location"}, + path_format_arguments=path_format_arguments, + **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) + + @distributed_trace_async + async def get_remote_connection( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> JSON: + """Gets RDP Connection info. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "rdpConnectionUrl": "str", # Optional. Link to open a Remote Desktop + session. + "webUrl": "str" # Optional. URL to open a browser based RDP session. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_remote_connection_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + +class EnvironmentsOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.developer.devcenter.aio.DevCenterClient`'s + :attr:`environments` attribute. + """ + + 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_environments(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> AsyncIterable[JSON]: + """Lists the environments for a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_environments_request( + project_name=project_name, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_environments_by_user( + self, project_name: str, user_id: str = "me", *, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists the environments for a project and user. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_environments_by_user_request( + project_name=project_name, + user_id=user_id, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_environment_by_user( + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> JSON: + """Gets an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_environments_get_environment_by_user_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + async def _create_or_update_environment_initial( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> JSON: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_create_or_update_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 201: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), response_headers) + + return cast(JSON, deserialized) + + @overload + async def begin_create_or_update_environment( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents a environment. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + + # response body for status code(s): 200, 201 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @overload + async def begin_create_or_update_environment( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents a environment. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @distributed_trace_async + async def begin_create_or_update_environment( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[JSON]: + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents a environment. Is either a model type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.AsyncLROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_environment_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + @overload + async def update_environment( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> JSON: + """Partially updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Updatable environment properties. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @overload + async def update_environment( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> JSON: + """Partially updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Updatable environment properties. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @distributed_trace_async + async def update_environment( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> JSON: + """Partially updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Updatable environment properties. Is either a model type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: + 'application/merge-patch+json'. Default value is None. + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + content_type = content_type or "application/merge-patch+json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_update_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + async def _delete_environment_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_environments_delete_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # 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) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @distributed_trace_async + async def begin_delete_environment( + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an environment and all it's associated resources. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + 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_environment_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + 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, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + async def _deploy_environment_action_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_deploy_environment_action_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @overload + async def begin_deploy_environment_action( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a deploy action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "actionId": "str", # The Catalog Item action id to execute. Required. + "parameters": {} # Optional. Parameters object for the Action. + } + """ + + @overload + async def begin_deploy_environment_action( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a deploy action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_deploy_environment_action( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a deploy action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Is either a model + type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[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._deploy_environment_action_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + async def _delete_environment_action_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_delete_environment_action_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @overload + async def begin_delete_environment_action( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a delete action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "actionId": "str", # The Catalog Item action id to execute. Required. + "parameters": {} # Optional. Parameters object for the Action. + } + """ + + @overload + async def begin_delete_environment_action( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a delete action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_delete_environment_action( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a delete action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Is either a model + type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[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_environment_action_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + async def _custom_environment_action_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_custom_environment_action_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @overload + async def begin_custom_environment_action( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a custom action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "actionId": "str", # The Catalog Item action id to execute. Required. + "parameters": {} # Optional. Parameters object for the Action. + } + """ + + @overload + async def begin_custom_environment_action( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a custom action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_custom_environment_action( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> AsyncLROPoller[None]: + """Executes a custom action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Is either a model + type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. 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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[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._custom_environment_action_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + @distributed_trace + def list_artifacts_by_environment( + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists the artifacts for an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "createdTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + created. + "downloadUri": "str", # Optional. Uri where the file contents can be + downloaded. + "fileSize": 0.0, # Optional. Size of file in bytes, if the artifact is a + file. + "id": "str", # Optional. Artifact identifier. + "isDirectory": bool, # Optional. Whether artifact is a directory. + "lastModifiedTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + last modified. + "name": "str" # Optional. Artifact name. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_artifacts_by_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_artifacts_by_environment_and_path( + self, project_name: str, environment_name: str, artifact_path: str, user_id: str = "me", **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists the artifacts for an environment at a specified path, or returns the file at the path. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param artifact_path: The path of the artifact. Required. + :type artifact_path: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "createdTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + created. + "downloadUri": "str", # Optional. Uri where the file contents can be + downloaded. + "fileSize": 0.0, # Optional. Size of file in bytes, if the artifact is a + file. + "id": "str", # Optional. Artifact identifier. + "isDirectory": bool, # Optional. Whether artifact is a directory. + "lastModifiedTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + last modified. + "name": "str" # Optional. Artifact name. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_artifacts_by_environment_and_path_request( + project_name=project_name, + environment_name=environment_name, + artifact_path=artifact_path, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_catalog_items(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> AsyncIterable[JSON]: + """Lists latest version of all catalog items available for a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "catalogName": "str", # Optional. Name of the catalog. + "id": "str", # Optional. Unique identifier of the catalog item. + "name": "str" # Optional. Name of the catalog item. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_catalog_items_request( + project_name=project_name, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_catalog_item(self, project_name: str, catalog_item_id: str, **kwargs: Any) -> JSON: + """Get a catalog item from a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param catalog_item_id: The unique id of the catalog item. Required. + :type catalog_item_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "catalogName": "str", # Optional. Name of the catalog. + "id": "str", # Optional. Unique identifier of the catalog item. + "name": "str" # Optional. Name of the catalog item. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_environments_get_catalog_item_request( + project_name=project_name, + catalog_item_id=catalog_item_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_catalog_item_versions( + self, project_name: str, catalog_item_id: str, *, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable[JSON]: + """List all versions of a catalog item from a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param catalog_item_id: The unique id of the catalog item. Required. + :type catalog_item_id: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "actions": [ + { + "description": "str", # Optional. Description of the action. + "id": "str", # Optional. Unique identifier of the action. + "name": "str", # Optional. Display name of the action. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed + values. + ], + "default": {}, # Optional. Default value of + the parameter. + "description": "str", # Optional. + Description of the parameter. + "id": "str", # Optional. Unique ID of the + parameter. + "name": "str", # Optional. Display name of + the parameter. + "readOnly": bool, # Optional. Whether or not + this parameter is read-only. If true, default should have a + value. + "required": bool, # Optional. Whether or not + this parameter is required. + "type": "str" # Optional. A string of one of + the basic JSON types (number, integer, null, array, object, + boolean, string). Known values are: "array", "boolean", + "integer", "null", "number", "object", and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining + the parameters specific to the custom action. + "runner": "str", # Optional. The container image to use to + execute the action. + "type": "str", # Optional. The action type. Known values + are: "Custom", "Deploy", and "Delete". + "typeName": "str" # Optional. Name of the custom action + type. + } + ], + "catalogItemId": "str", # Optional. Unique identifier of the catalog item. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. A long description of the catalog item. + "eligibleForLatestVersion": bool, # Optional. Whether the version is + eligible to be the latest version. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed values. + ], + "default": {}, # Optional. Default value of the parameter. + "description": "str", # Optional. Description of the + parameter. + "id": "str", # Optional. Unique ID of the parameter. + "name": "str", # Optional. Display name of the parameter. + "readOnly": bool, # Optional. Whether or not this parameter + is read-only. If true, default should have a value. + "required": bool, # Optional. Whether or not this parameter + is required. + "type": "str" # Optional. A string of one of the basic JSON + types (number, integer, null, array, object, boolean, string). Known + values are: "array", "boolean", "integer", "null", "number", "object", + and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining the parameters + object passed to actions. + "runner": "str", # Optional. The default container image to use to execute + actions. + "status": "str", # Optional. Defines whether the specific catalog item + version can be used. Known values are: "Enabled" and "Disabled". + "summary": "str", # Optional. A short summary of the catalog item. + "templatePath": "str", # Optional. Path to the catalog item entrypoint file. + "version": "str" # Optional. The version of the catalog item. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_catalog_item_versions_request( + project_name=project_name, + catalog_item_id=catalog_item_id, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get_catalog_item_version( + self, project_name: str, catalog_item_id: str, version: str, **kwargs: Any + ) -> JSON: + """Get a specific catalog item version from a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param catalog_item_id: The unique id of the catalog item. Required. + :type catalog_item_id: str + :param version: The version of the catalog item. Required. + :type version: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "actions": [ + { + "description": "str", # Optional. Description of the action. + "id": "str", # Optional. Unique identifier of the action. + "name": "str", # Optional. Display name of the action. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed + values. + ], + "default": {}, # Optional. Default value of + the parameter. + "description": "str", # Optional. + Description of the parameter. + "id": "str", # Optional. Unique ID of the + parameter. + "name": "str", # Optional. Display name of + the parameter. + "readOnly": bool, # Optional. Whether or not + this parameter is read-only. If true, default should have a + value. + "required": bool, # Optional. Whether or not + this parameter is required. + "type": "str" # Optional. A string of one of + the basic JSON types (number, integer, null, array, object, + boolean, string). Known values are: "array", "boolean", + "integer", "null", "number", "object", and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining + the parameters specific to the custom action. + "runner": "str", # Optional. The container image to use to + execute the action. + "type": "str", # Optional. The action type. Known values + are: "Custom", "Deploy", and "Delete". + "typeName": "str" # Optional. Name of the custom action + type. + } + ], + "catalogItemId": "str", # Optional. Unique identifier of the catalog item. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. A long description of the catalog item. + "eligibleForLatestVersion": bool, # Optional. Whether the version is + eligible to be the latest version. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed values. + ], + "default": {}, # Optional. Default value of the parameter. + "description": "str", # Optional. Description of the + parameter. + "id": "str", # Optional. Unique ID of the parameter. + "name": "str", # Optional. Display name of the parameter. + "readOnly": bool, # Optional. Whether or not this parameter + is read-only. If true, default should have a value. + "required": bool, # Optional. Whether or not this parameter + is required. + "type": "str" # Optional. A string of one of the basic JSON + types (number, integer, null, array, object, boolean, string). Known + values are: "array", "boolean", "integer", "null", "number", "object", + and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining the parameters + object passed to actions. + "runner": "str", # Optional. The default container image to use to execute + actions. + "status": "str", # Optional. Defines whether the specific catalog item + version can be used. Known values are: "Enabled" and "Disabled". + "summary": "str", # Optional. A short summary of the catalog item. + "templatePath": "str", # Optional. Path to the catalog item entrypoint file. + "version": "str" # Optional. The version of the catalog item. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_environments_get_catalog_item_version_request( + project_name=project_name, + catalog_item_id=catalog_item_id, + version=version, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_environment_types( + self, project_name: str, *, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable[JSON]: + """Lists all environment types configured for a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "deploymentTargetId": "str", # Optional. Id of a subscription or management + group that the environment type will be mapped to. The environment's resources + will be deployed into this subscription or management group. + "name": "str", # Optional. Name of the environment type. + "status": "str" # Optional. Defines whether this Environment Type can be + used in this Project. Known values are: "Enabled" and "Disabled". + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_environment_types_request( + project_name=project_name, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/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/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/__init__.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/__init__.py new file mode 100644 index 000000000000..7350c68142b7 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for 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 ._operations import DevCenterOperations +from ._operations import DevBoxesOperations +from ._operations import EnvironmentsOperations + +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__ = [ + "DevCenterOperations", + "DevBoxesOperations", + "EnvironmentsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/_operations.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/_operations.py new file mode 100644 index 000000000000..547059c56ade --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/_operations.py @@ -0,0 +1,6274 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from urllib.parse import parse_qs, urljoin, urlparse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.polling.base_polling import LROBasePolling +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .._serialization import Serializer +from .._vendor import _format_url_section + +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 +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_dev_center_list_projects_request( + *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_center_get_project_request(project_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_center_list_all_dev_boxes_request( + *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/devboxes" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_center_list_all_dev_boxes_by_user_request( + user_id: str = "me", *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/users/{userId}/devboxes" + path_format_arguments = { + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_list_pools_request( + project_name: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/pools" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_get_pool_request(pool_name: str, project_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/pools/{poolName}" + path_format_arguments = { + "poolName": _SERIALIZER.url( + "pool_name", pool_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$" + ), + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_list_schedules_by_pool_request( + project_name: str, pool_name: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/pools/{poolName}/schedules" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "poolName": _SERIALIZER.url( + "pool_name", pool_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_get_schedule_by_pool_request( + project_name: str, pool_name: str, schedule_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/pools/{poolName}/schedules/{scheduleName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "poolName": _SERIALIZER.url( + "pool_name", pool_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$" + ), + "scheduleName": _SERIALIZER.url("schedule_name", schedule_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_list_dev_boxes_by_user_request( + project_name: str, user_id: str = "me", *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/devboxes" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_get_dev_box_by_user_request( + project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/devboxes/{devBoxName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "devBoxName": _SERIALIZER.url( + "dev_box_name", + dev_box_name, + "str", + max_length=63, + min_length=3, + pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_create_dev_box_request( + project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/devboxes/{devBoxName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "devBoxName": _SERIALIZER.url( + "dev_box_name", + dev_box_name, + "str", + max_length=63, + min_length=3, + pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_delete_dev_box_request( + project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/devboxes/{devBoxName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "devBoxName": _SERIALIZER.url( + "dev_box_name", + dev_box_name, + "str", + max_length=63, + min_length=3, + pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_start_dev_box_request( + project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/devboxes/{devBoxName}:start" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "devBoxName": _SERIALIZER.url( + "dev_box_name", + dev_box_name, + "str", + max_length=63, + min_length=3, + pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_stop_dev_box_request( + project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/devboxes/{devBoxName}:stop" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "devBoxName": _SERIALIZER.url( + "dev_box_name", + dev_box_name, + "str", + max_length=63, + min_length=3, + pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dev_boxes_get_remote_connection_request( + project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/devboxes/{devBoxName}/remoteConnection" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "devBoxName": _SERIALIZER.url( + "dev_box_name", + dev_box_name, + "str", + max_length=63, + min_length=3, + pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-_.]{2,62}$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_list_environments_request( + project_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/environments" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_list_environments_by_user_request( + project_name: str, user_id: str = "me", *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_get_environment_by_user_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_create_or_update_environment_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_update_environment_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_delete_environment_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_deploy_environment_action_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}:deploy" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_delete_environment_action_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}:delete" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_custom_environment_action_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}:custom" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_list_artifacts_by_environment_request( + project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}/artifacts" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_list_artifacts_by_environment_and_path_request( + project_name: str, environment_name: str, artifact_path: str, user_id: str = "me", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/users/{userId}/environments/{environmentName}/artifacts/{artifactPath}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "userId": _SERIALIZER.url( + "user_id", + user_id, + "str", + max_length=36, + min_length=2, + pattern=r"^[a-zA-Z0-9]{8}-([a-zA-Z0-9]{4}-){3}[a-zA-Z0-9]{12}$|^me$", + ), + "environmentName": _SERIALIZER.url("environment_name", environment_name, "str"), + "artifactPath": _SERIALIZER.url("artifact_path", artifact_path, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_list_catalog_items_request( + project_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/catalogItems" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_get_catalog_item_request(project_name: str, catalog_item_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/catalogItems/{catalogItemId}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "catalogItemId": _SERIALIZER.url("catalog_item_id", catalog_item_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_list_catalog_item_versions_request( + project_name: str, catalog_item_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/catalogItems/{catalogItemId}/versions" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "catalogItemId": _SERIALIZER.url("catalog_item_id", catalog_item_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_get_catalog_item_version_request( + project_name: str, catalog_item_id: str, version: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/catalogItems/{catalogItemId}/versions/{version}" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + "catalogItemId": _SERIALIZER.url("catalog_item_id", catalog_item_id, "str"), + "version": _SERIALIZER.url("version", version, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_environments_list_environment_types_request( + project_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/projects/{projectName}/environmentTypes" + path_format_arguments = { + "projectName": _SERIALIZER.url( + "project_name", project_name, "str", max_length=63, min_length=3, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9-]{2,62}$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DevCenterOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.developer.devcenter.DevCenterClient`'s + :attr:`dev_center` attribute. + """ + + 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_projects( + self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> Iterable[JSON]: + """Lists all projects. + + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "description": "str", # Optional. Description of the project. + "name": "str" # Optional. Name of the project. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_center_list_projects_request( + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_project(self, project_name: str, **kwargs: Any) -> JSON: + """Gets a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "description": "str", # Optional. Description of the project. + "name": "str" # Optional. Name of the project. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_center_get_project_request( + project_name=project_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_all_dev_boxes( + self, *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> Iterable[JSON]: + """Lists Dev Boxes that the caller has access to in the DevCenter. + + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_center_list_all_dev_boxes_request( + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_all_dev_boxes_by_user( + self, user_id: str = "me", *, filter: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> Iterable[JSON]: + """Lists Dev Boxes in the Dev Center for a particular user. + + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_center_list_all_dev_boxes_by_user_request( + user_id=user_id, + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class DevBoxesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.developer.devcenter.DevCenterClient`'s + :attr:`dev_boxes` attribute. + """ + + 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_pools( + self, project_name: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable[JSON]: + """Lists available pools. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether owners of Dev + Boxes in this pool are local administrators on the Dev Boxes. Known values are: + "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where Dev Boxes in the pool are + located. + "name": "str", # Optional. Pool name. + "osType": "str", # Optional. The operating system type of Dev Boxes in this + pool. "Windows" + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + } + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_boxes_list_pools_request( + project_name=project_name, + top=top, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_pool(self, pool_name: str, project_name: str, **kwargs: Any) -> JSON: + """Gets a pool. + + :param pool_name: The name of a pool of Dev Boxes. Required. + :type pool_name: str + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether owners of Dev + Boxes in this pool are local administrators on the Dev Boxes. Known values are: + "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where Dev Boxes in the pool are + located. + "name": "str", # Optional. Pool name. + "osType": "str", # Optional. The operating system type of Dev Boxes in this + pool. "Windows" + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + } + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_pool_request( + pool_name=pool_name, + project_name=project_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_schedules_by_pool( + self, + project_name: str, + pool_name: str, + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable[JSON]: + """Lists available schedules for a pool. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param pool_name: The name of a pool of Dev Boxes. Required. + :type pool_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "frequency": "str", # Optional. The frequency of this scheduled task. + "Daily" + "name": "str", # Optional. Display name for the Schedule. + "time": "str", # Optional. The target time to trigger the action. The format + is HH:MM. + "timeZone": "str", # Optional. The IANA timezone id at which the schedule + should execute. + "type": "str" # Optional. Supported type this scheduled task represents. + "StopDevBox" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_boxes_list_schedules_by_pool_request( + project_name=project_name, + pool_name=pool_name, + top=top, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_schedule_by_pool(self, project_name: str, pool_name: str, schedule_name: str, **kwargs: Any) -> JSON: + """Gets a schedule. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param pool_name: The name of a pool of Dev Boxes. Required. + :type pool_name: str + :param schedule_name: The name of a schedule. Required. + :type schedule_name: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "frequency": "str", # Optional. The frequency of this scheduled task. + "Daily" + "name": "str", # Optional. Display name for the Schedule. + "time": "str", # Optional. The target time to trigger the action. The format + is HH:MM. + "timeZone": "str", # Optional. The IANA timezone id at which the schedule + should execute. + "type": "str" # Optional. Supported type this scheduled task represents. + "StopDevBox" + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_schedule_by_pool_request( + project_name=project_name, + pool_name=pool_name, + schedule_name=schedule_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_dev_boxes_by_user( + self, + project_name: str, + user_id: str = "me", + *, + filter: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> Iterable[JSON]: + """Lists Dev Boxes in the project for a particular user. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword filter: An OData filter clause to apply to the operation. Default value is None. + :paramtype filter: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_dev_boxes_list_dev_boxes_by_user_request( + project_name=project_name, + user_id=user_id, + filter=filter, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_dev_box_by_user(self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any) -> JSON: + """Gets a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_dev_box_by_user_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + def _create_dev_box_initial( + self, project_name: str, dev_box_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> JSON: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_dev_boxes_create_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 201: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @overload + def begin_create_dev_box( + self, + project_name: str, + dev_box_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[JSON]: + """Creates or updates a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents a environment. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + + # response body for status code(s): 200, 201 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + + @overload + def begin_create_dev_box( + self, + project_name: str, + dev_box_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[JSON]: + """Creates or updates a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents a environment. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + + @distributed_trace + def begin_create_dev_box( + self, project_name: str, dev_box_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> LROPoller[JSON]: + """Creates or updates a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param body: Represents a environment. Is either a model type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + def _delete_dev_box_initial( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> Optional[JSON]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[JSON]] + + request = build_dev_boxes_delete_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # 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) + + deserialized = None + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace + def begin_delete_dev_box( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> LROPoller[JSON]: + """Deletes a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **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) + + def _start_dev_box_initial( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> Optional[JSON]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[JSON]] + + request = build_dev_boxes_start_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace + def begin_start_dev_box( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> LROPoller[JSON]: + """Starts a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "location"}, + path_format_arguments=path_format_arguments, + **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) + + def _stop_dev_box_initial( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> Optional[JSON]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[JSON]] + + request = build_dev_boxes_stop_dev_box_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace + def begin_stop_dev_box( + self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any + ) -> LROPoller[JSON]: + """Stops a Dev Box. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "poolName": "str", # The name of the Dev Box pool this machine belongs to. + Required. + "actionState": "str", # Optional. The current action state of the Dev Box. + This is state is based on previous action performed by user. + "createdTime": "2020-02-20 00:00:00", # Optional. Creation time of this Dev + Box. + "errorDetails": { + "code": "str", # Optional. The error code. + "message": "str" # Optional. The error message. + }, + "hardwareProfile": { + "memoryGB": 0, # Optional. The amount of memory available for the + Dev Box. + "skuName": "str", # Optional. The name of the SKU. + "vCPUs": 0 # Optional. The number of vCPUs available for the Dev + Box. + }, + "imageReference": { + "name": "str", # Optional. The name of the image used. + "operatingSystem": "str", # Optional. The operating system of the + image. + "osBuildNumber": "str", # Optional. The operating system build + number of the image. + "publishedDate": "2020-02-20 00:00:00", # Optional. The datetime + that the backing image version was published. + "version": "str" # Optional. The version of the image. + }, + "localAdministrator": "str", # Optional. Indicates whether the owner of the + Dev Box is a local administrator. Known values are: "Enabled" and "Disabled". + "location": "str", # Optional. Azure region where this Dev Box is located. + This will be the same region as the Virtual Network it is attached to. + "name": "str", # Optional. Display name for the Dev Box. + "osType": "str", # Optional. The operating system type of this Dev Box. + "Windows" + "powerState": "str", # Optional. The current power state of the Dev Box. + Known values are: "Unknown", "Deallocated", "PoweredOff", "Running", and + "Hibernated". + "projectName": "str", # Optional. Name of the project this Dev Box belongs + to. + "provisioningState": "str", # Optional. The current provisioning state of + the Dev Box. + "storageProfile": { + "osDisk": { + "diskSizeGB": 0 # Optional. The size of the OS Disk in + gigabytes. + } + }, + "uniqueId": "str", # Optional. A unique identifier for the Dev Box. This is + a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + "user": "str" # Optional. User identifier of the user this vm is assigned + to. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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._stop_dev_box_initial( # type: ignore + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "location"}, + path_format_arguments=path_format_arguments, + **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) + + @distributed_trace + def get_remote_connection(self, project_name: str, dev_box_name: str, user_id: str = "me", **kwargs: Any) -> JSON: + """Gets RDP Connection info. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param dev_box_name: The name of a Dev Box. Required. + :type dev_box_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "rdpConnectionUrl": "str", # Optional. Link to open a Remote Desktop + session. + "webUrl": "str" # Optional. URL to open a browser based RDP session. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_dev_boxes_get_remote_connection_request( + project_name=project_name, + dev_box_name=dev_box_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + +class EnvironmentsOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.developer.devcenter.DevCenterClient`'s + :attr:`environments` attribute. + """ + + 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_environments(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> Iterable[JSON]: + """Lists the environments for a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_environments_request( + project_name=project_name, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_environments_by_user( + self, project_name: str, user_id: str = "me", *, top: Optional[int] = None, **kwargs: Any + ) -> Iterable[JSON]: + """Lists the environments for a project and user. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_environments_by_user_request( + project_name=project_name, + user_id=user_id, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_environment_by_user( + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> JSON: + """Gets an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_environments_get_environment_by_user_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + def _create_or_update_environment_initial( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> JSON: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_create_or_update_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 200: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if response.status_code == 201: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), response_headers) + + return cast(JSON, deserialized) + + @overload + def begin_create_or_update_environment( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[JSON]: + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents a environment. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + + # response body for status code(s): 200, 201 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @overload + def begin_create_or_update_environment( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[JSON]: + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents a environment. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @distributed_trace + def begin_create_or_update_environment( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> LROPoller[JSON]: + """Creates or updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Represents a environment. Is either a model type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 JSON object + :rtype: ~azure.core.polling.LROPoller[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200, 201 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + 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_environment_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + @overload + def update_environment( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> JSON: + """Partially updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Updatable environment properties. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @overload + def update_environment( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> JSON: + """Partially updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Updatable environment properties. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + + @distributed_trace + def update_environment( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> JSON: + """Partially updates an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Updatable environment properties. Is either a model type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: + 'application/merge-patch+json'. Default value is None. + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "environmentType": "str", # Environment type. Required. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. Description of the Environment. + "name": "str", # Optional. Environment name. + "owner": "str", # Optional. Identifier of the owner of this Environment. + "parameters": {}, # Optional. Parameters object for the deploy action. + "provisioningState": "str", # Optional. The provisioning state of the + environment. + "resourceGroupId": "str", # Optional. The identifier of the resource group + containing the environment's resources. + "scheduledTasks": { + "str": { + "startTime": "2020-02-20 00:00:00", # Date/time by which the + environment should expire. Required. + "type": "str", # Supported type this scheduled task + represents. Required. "AutoExpire" + "enabled": "str" # Optional. Indicates whether or not this + scheduled task is enabled. Known values are: "Enabled" and "Disabled". + } + }, + "tags": { + "str": "str" # Optional. Key value pairs that will be applied to + resources deployed in this environment as tags. + } + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + content_type = content_type or "application/merge-patch+json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_update_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + def _delete_environment_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_environments_delete_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # 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) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @distributed_trace + def begin_delete_environment( + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> LROPoller[None]: + """Deletes an environment and all it's associated resources. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + 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_environment_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + 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, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + def _deploy_environment_action_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_deploy_environment_action_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @overload + def begin_deploy_environment_action( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Executes a deploy action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "actionId": "str", # The Catalog Item action id to execute. Required. + "parameters": {} # Optional. Parameters object for the Action. + } + """ + + @overload + def begin_deploy_environment_action( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Executes a deploy action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_deploy_environment_action( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> LROPoller[None]: + """Executes a deploy action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Is either a model + type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[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._deploy_environment_action_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + def _delete_environment_action_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_delete_environment_action_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @overload + def begin_delete_environment_action( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Executes a delete action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "actionId": "str", # The Catalog Item action id to execute. Required. + "parameters": {} # Optional. Parameters object for the Action. + } + """ + + @overload + def begin_delete_environment_action( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Executes a delete action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_delete_environment_action( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> LROPoller[None]: + """Executes a delete action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Is either a model + type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[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_environment_action_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + def _custom_environment_action_initial( # pylint: disable=inconsistent-return-statements + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_environments_custom_environment_action_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + if response.status_code == 202: + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + if cls: + return cls(pipeline_response, None, response_headers) + + @overload + def begin_custom_environment_action( + self, + project_name: str, + environment_name: str, + body: JSON, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Executes a custom action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: JSON + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "actionId": "str", # The Catalog Item action id to execute. Required. + "parameters": {} # Optional. Parameters object for the Action. + } + """ + + @overload + def begin_custom_environment_action( + self, + project_name: str, + environment_name: str, + body: IO, + user_id: str = "me", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Executes a custom action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Required. + :type body: IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_custom_environment_action( + self, project_name: str, environment_name: str, body: Union[JSON, IO], user_id: str = "me", **kwargs: Any + ) -> LROPoller[None]: + """Executes a custom action. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param body: Action properties overriding the environment's default values. Is either a model + type or a IO type. Required. + :type body: JSON or IO + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. 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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[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._custom_environment_action_initial( # type: ignore + project_name=project_name, + environment_name=environment_name, + body=body, + user_id=user_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + + if polling is True: + polling_method = cast( + PollingMethod, + LROBasePolling( + lro_delay, + lro_options={"final-state-via": "original-uri"}, + path_format_arguments=path_format_arguments, + **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) + + @distributed_trace + def list_artifacts_by_environment( + self, project_name: str, environment_name: str, user_id: str = "me", **kwargs: Any + ) -> Iterable[JSON]: + """Lists the artifacts for an environment. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "createdTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + created. + "downloadUri": "str", # Optional. Uri where the file contents can be + downloaded. + "fileSize": 0.0, # Optional. Size of file in bytes, if the artifact is a + file. + "id": "str", # Optional. Artifact identifier. + "isDirectory": bool, # Optional. Whether artifact is a directory. + "lastModifiedTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + last modified. + "name": "str" # Optional. Artifact name. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_artifacts_by_environment_request( + project_name=project_name, + environment_name=environment_name, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_artifacts_by_environment_and_path( + self, project_name: str, environment_name: str, artifact_path: str, user_id: str = "me", **kwargs: Any + ) -> Iterable[JSON]: + """Lists the artifacts for an environment at a specified path, or returns the file at the path. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param environment_name: The name of the environment. Required. + :type environment_name: str + :param artifact_path: The path of the artifact. Required. + :type artifact_path: str + :param user_id: The AAD object id of the user. If value is 'me', the identity is taken from the + authentication context. Default value is "me". + :type user_id: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "createdTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + created. + "downloadUri": "str", # Optional. Uri where the file contents can be + downloaded. + "fileSize": 0.0, # Optional. Size of file in bytes, if the artifact is a + file. + "id": "str", # Optional. Artifact identifier. + "isDirectory": bool, # Optional. Whether artifact is a directory. + "lastModifiedTime": "2020-02-20 00:00:00", # Optional. Time the artifact was + last modified. + "name": "str" # Optional. Artifact name. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_artifacts_by_environment_and_path_request( + project_name=project_name, + environment_name=environment_name, + artifact_path=artifact_path, + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_catalog_items(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> Iterable[JSON]: + """Lists latest version of all catalog items available for a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "catalogName": "str", # Optional. Name of the catalog. + "id": "str", # Optional. Unique identifier of the catalog item. + "name": "str" # Optional. Name of the catalog item. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_catalog_items_request( + project_name=project_name, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_catalog_item(self, project_name: str, catalog_item_id: str, **kwargs: Any) -> JSON: + """Get a catalog item from a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param catalog_item_id: The unique id of the catalog item. Required. + :type catalog_item_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "catalogName": "str", # Optional. Name of the catalog. + "id": "str", # Optional. Unique identifier of the catalog item. + "name": "str" # Optional. Name of the catalog item. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_environments_get_catalog_item_request( + project_name=project_name, + catalog_item_id=catalog_item_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_catalog_item_versions( + self, project_name: str, catalog_item_id: str, *, top: Optional[int] = None, **kwargs: Any + ) -> Iterable[JSON]: + """List all versions of a catalog item from a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param catalog_item_id: The unique id of the catalog item. Required. + :type catalog_item_id: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "actions": [ + { + "description": "str", # Optional. Description of the action. + "id": "str", # Optional. Unique identifier of the action. + "name": "str", # Optional. Display name of the action. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed + values. + ], + "default": {}, # Optional. Default value of + the parameter. + "description": "str", # Optional. + Description of the parameter. + "id": "str", # Optional. Unique ID of the + parameter. + "name": "str", # Optional. Display name of + the parameter. + "readOnly": bool, # Optional. Whether or not + this parameter is read-only. If true, default should have a + value. + "required": bool, # Optional. Whether or not + this parameter is required. + "type": "str" # Optional. A string of one of + the basic JSON types (number, integer, null, array, object, + boolean, string). Known values are: "array", "boolean", + "integer", "null", "number", "object", and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining + the parameters specific to the custom action. + "runner": "str", # Optional. The container image to use to + execute the action. + "type": "str", # Optional. The action type. Known values + are: "Custom", "Deploy", and "Delete". + "typeName": "str" # Optional. Name of the custom action + type. + } + ], + "catalogItemId": "str", # Optional. Unique identifier of the catalog item. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. A long description of the catalog item. + "eligibleForLatestVersion": bool, # Optional. Whether the version is + eligible to be the latest version. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed values. + ], + "default": {}, # Optional. Default value of the parameter. + "description": "str", # Optional. Description of the + parameter. + "id": "str", # Optional. Unique ID of the parameter. + "name": "str", # Optional. Display name of the parameter. + "readOnly": bool, # Optional. Whether or not this parameter + is read-only. If true, default should have a value. + "required": bool, # Optional. Whether or not this parameter + is required. + "type": "str" # Optional. A string of one of the basic JSON + types (number, integer, null, array, object, boolean, string). Known + values are: "array", "boolean", "integer", "null", "number", "object", + and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining the parameters + object passed to actions. + "runner": "str", # Optional. The default container image to use to execute + actions. + "status": "str", # Optional. Defines whether the specific catalog item + version can be used. Known values are: "Enabled" and "Disabled". + "summary": "str", # Optional. A short summary of the catalog item. + "templatePath": "str", # Optional. Path to the catalog item entrypoint file. + "version": "str" # Optional. The version of the catalog item. + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_catalog_item_versions_request( + project_name=project_name, + catalog_item_id=catalog_item_id, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_catalog_item_version(self, project_name: str, catalog_item_id: str, version: str, **kwargs: Any) -> JSON: + """Get a specific catalog item version from a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :param catalog_item_id: The unique id of the catalog item. Required. + :type catalog_item_id: str + :param version: The version of the catalog item. Required. + :type version: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "actions": [ + { + "description": "str", # Optional. Description of the action. + "id": "str", # Optional. Unique identifier of the action. + "name": "str", # Optional. Display name of the action. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed + values. + ], + "default": {}, # Optional. Default value of + the parameter. + "description": "str", # Optional. + Description of the parameter. + "id": "str", # Optional. Unique ID of the + parameter. + "name": "str", # Optional. Display name of + the parameter. + "readOnly": bool, # Optional. Whether or not + this parameter is read-only. If true, default should have a + value. + "required": bool, # Optional. Whether or not + this parameter is required. + "type": "str" # Optional. A string of one of + the basic JSON types (number, integer, null, array, object, + boolean, string). Known values are: "array", "boolean", + "integer", "null", "number", "object", and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining + the parameters specific to the custom action. + "runner": "str", # Optional. The container image to use to + execute the action. + "type": "str", # Optional. The action type. Known values + are: "Custom", "Deploy", and "Delete". + "typeName": "str" # Optional. Name of the custom action + type. + } + ], + "catalogItemId": "str", # Optional. Unique identifier of the catalog item. + "catalogItemName": "str", # Optional. Name of the catalog item. + "catalogName": "str", # Optional. Name of the catalog. + "description": "str", # Optional. A long description of the catalog item. + "eligibleForLatestVersion": bool, # Optional. Whether the version is + eligible to be the latest version. + "parameters": [ + { + "allowed": [ + {} # Optional. An array of allowed values. + ], + "default": {}, # Optional. Default value of the parameter. + "description": "str", # Optional. Description of the + parameter. + "id": "str", # Optional. Unique ID of the parameter. + "name": "str", # Optional. Display name of the parameter. + "readOnly": bool, # Optional. Whether or not this parameter + is read-only. If true, default should have a value. + "required": bool, # Optional. Whether or not this parameter + is required. + "type": "str" # Optional. A string of one of the basic JSON + types (number, integer, null, array, object, boolean, string). Known + values are: "array", "boolean", "integer", "null", "number", "object", + and "string". + } + ], + "parametersSchema": "str", # Optional. JSON schema defining the parameters + object passed to actions. + "runner": "str", # Optional. The default container image to use to execute + actions. + "status": "str", # Optional. Defines whether the specific catalog item + version can be used. Known values are: "Enabled" and "Disabled". + "summary": "str", # Optional. A short summary of the catalog item. + "templatePath": "str", # Optional. Path to the catalog item entrypoint file. + "version": "str" # Optional. The version of the catalog item. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + request = build_environments_get_catalog_item_version_request( + project_name=project_name, + catalog_item_id=catalog_item_id, + version=version, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def list_environment_types(self, project_name: str, *, top: Optional[int] = None, **kwargs: Any) -> Iterable[JSON]: + """Lists all environment types configured for a project. + + :param project_name: The DevCenter Project upon which to execute operations. Required. + :type project_name: str + :keyword top: The maximum number of resources to return from the operation. Example: 'top=10'. + Default value is None. + :paramtype top: int + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "deploymentTargetId": "str", # Optional. Id of a subscription or management + group that the environment type will be mapped to. The environment's resources + will be deployed into this subscription or management group. + "name": "str", # Optional. Name of the environment type. + "status": "str" # Optional. Defines whether this Environment Type can be + used in this Project. Known values are: "Enabled" and "Disabled". + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[JSON] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_environments_list_environment_types_request( + project_name=project_name, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + else: + # 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) + path_format_arguments = { + "tenantId": self._serialize.url( + "self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True + ), + "devCenter": self._serialize.url( + "self._config.dev_center", self._config.dev_center, "str", skip_quote=True + ), + "devCenterDnsSuffix": self._serialize.url( + "self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True + ), + } + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + + return request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["value"] + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.get("nextLink", None), iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/_patch.py b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/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/devcenter/azure-developer-devcenter/azure/developer/devcenter/py.typed b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/dev_requirements.txt b/sdk/devcenter/azure-developer-devcenter/dev_requirements.txt new file mode 100644 index 000000000000..c4e89ba26d71 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../tools/azure-devtools +-e ../../../tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +aiohttp \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/samples/create_devbox_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/create_devbox_sample.py new file mode 100644 index 000000000000..ec71b21795da --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/create_devbox_sample.py @@ -0,0 +1,83 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import logging +import os + +from azure.developer.devcenter import DevCenterClient +from azure.identity import DefaultAzureCredential +from azure.core.exceptions import HttpResponseError + +def get_project_name(LOG, client): + projects = list(client.projects.list_by_dev_center(top=1)) + return projects[0].name + +def main(): + logging.basicConfig(level=logging.DEBUG) + LOG = logging.getLogger() + + # Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: + # AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, DEVCENTER_NAME + try: + tenant_id = os.environ["AZURE_TENANT_ID"] + except KeyError: + LOG.error("Missing environment variable 'AZURE_TENANT_ID' - please set it before running the example") + exit() + + try: + dev_center_name = os.environ["DEVCENTER_NAME"] + except KeyError: + LOG.error("Missing environment variable 'DEVCENTER_NAME' - please set it before running the example") + exit() + + # Build a client through AAD + client = DevCenterClient(tenant_id, dev_center_name, credential=DefaultAzureCredential()) + + # Fetch control plane resource dependencies + projects = list(client.dev_center.list_projects(top=1)) + target_project_name = projects[0]['name'] + + pools = list(client.dev_boxes.list_pools(target_project_name, top=1)) + target_pool_name = pools[0]['name'] + + # Stand up a new dev box + create_response = client.dev_boxes.begin_create_dev_box(target_project_name, "Test_DevBox", {"poolName": target_pool_name}) + devbox_result = create_response.result() + + LOG.info(f"Provisioned dev box with status {devbox_result['provisioningState']}.") + + # Connect to the provisioned dev box + remote_connection_response = client.dev_boxes.get_remote_connection(target_project_name, "Test_DevBox") + LOG.info(f"Connect to the dev box using web URL {remote_connection_response['webUrl']}") + + # Tear down the dev box when finished + delete_response = client.dev_boxes.begin_delete_dev_box(target_project_name, "Test_DevBox") + delete_response.wait() + LOG.info("Deleted dev box successfully.") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/samples/create_environment_sample.py b/sdk/devcenter/azure-developer-devcenter/samples/create_environment_sample.py new file mode 100644 index 000000000000..ab386f53ae94 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/samples/create_environment_sample.py @@ -0,0 +1,81 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- +import logging +import os + +from azure.developer.devcenter import DevCenterClient +from azure.identity import DefaultAzureCredential +from azure.core.exceptions import HttpResponseError + +def main(): + logging.basicConfig(level=logging.DEBUG) + LOG = logging.getLogger() + + # Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: + # AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, DEVCENTER_NAME + try: + tenant_id = os.environ["AZURE_TENANT_ID"] + except KeyError: + LOG.error("Missing environment variable 'AZURE_TENANT_ID' - please set if before running the example") + exit() + + try: + dev_center_name = os.environ["DEVCENTER_NAME"] + except KeyError: + LOG.error("Missing environment variable 'DEVCENTER_NAME' - please set if before running the example") + exit() + + # Build a client through AAD + client = DevCenterClient(tenant_id, dev_center_name, credential=DefaultAzureCredential()) + + # Fetch control plane resource dependencies + target_project_name = list(client.dev_center.list_projects(top=1))[0]['name'] + target_catalog_item_name = list(client.environments.list_catalog_items(target_project_name, top=1))[0]['name'] + target_environment_type_name = list(client.environments.list_environment_types(target_project_name, top=1))[0]['name'] + + # Stand up a new environment + create_response = client.environments.begin_create_environment(target_project_name, + "Dev_Environment", + {"catalogItemName": target_catalog_item_name, "environmentType": target_environment_type_name}) + environment_result = create_response.result() + + LOG.info(f"Provisioned environment with status {environment_result['provisioningState']}.") + + # Fetch deployment artifacts + artifact_response = client.environments.list_artifacts_by_environment(target_project_name, "Dev_Environment") + + for artifact in artifact_response: + LOG.info(artifact) + + # Tear down the environment when finished + delete_response = client.environments.begin_delete_environment(target_project_name, "Dev_Environment") + delete_response.wait() + LOG.info("Completed deletion for the environment.") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/setup.py b/sdk/devcenter/azure-developer-devcenter/setup.py new file mode 100644 index 000000000000..ba7ccc0e80c2 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/setup.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# coding: utf-8 + +import os +import re +from setuptools import setup, find_packages + + +PACKAGE_NAME = "azure-developer-devcenter" +PACKAGE_PPRINT_NAME = "Azure Developer DevCenter Service" + +# a-b-c => a/b/c +package_folder_path = PACKAGE_NAME.replace("-", "/") + +# Version extraction inspired from 'requests' +with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) + +if not version: + raise RuntimeError("Cannot find version information") + + +setup( + name=PACKAGE_NAME, + version=version, + description="Microsoft Azure Developer DevCenter Service Client Library for Python", + long_description=open("README.md", "r").read(), + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", + keywords="azure, azure sdk", + classifiers=[ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "License :: OSI Approved :: MIT License", + ], + zip_safe=False, + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.developer", + ] + ), + include_package_data=True, + package_data={ + "pytyped": ["py.typed"], + }, + install_requires=[ + "isodate<1.0.0,>=0.6.1", + "azure-core<2.0.0,>=1.24.0", + ], + python_requires=">=3.7", +) diff --git a/sdk/devcenter/azure-developer-devcenter/swagger/README.md b/sdk/devcenter/azure-developer-devcenter/swagger/README.md new file mode 100644 index 000000000000..3d91b6b70e74 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/swagger/README.md @@ -0,0 +1,26 @@ +### Settings + +```yaml +input-file: + - https://github.com/Azure/azure-rest-api-specs/blob/5a024c0e76424caaca36166ba41cee6f3f1f8add/specification/devcenter/data-plane/Microsoft.DevCenter/preview/2022-03-01-preview/devcenter.json + - https://github.com/Azure/azure-rest-api-specs/blob/5a024c0e76424caaca36166ba41cee6f3f1f8add/specification/devcenter/data-plane/Microsoft.DevCenter/preview/2022-03-01-preview/devbox.json + - https://github.com/Azure/azure-rest-api-specs/blob/5a024c0e76424caaca36166ba41cee6f3f1f8add/specification/devcenter/data-plane/Microsoft.DevCenter/preview/2022-03-01-preview/environments.json +output-folder: ../azure/developer/devcenter +namespace: azure.developer.devcenter +package-name: azure-developer-devcenter +license-header: MICROSOFT_MIT_NO_VERSION +title: DevCenterClient +package-version: 1.0.0b1 +package-mode: dataplane +package-pprint-name: Azure Developer DevCenter Service +security: AADToken +security-scopes: https://devcenter.azure.com/.default +``` + +### Put project as a method param, since Python will generate only one client +``` yaml +directive: +- from: swagger-document + where: $.parameters["ProjectNameParameter"] + transform: $["x-ms-parameter-location"] = "method" +``` \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/tests/conftest.py b/sdk/devcenter/azure-developer-devcenter/tests/conftest.py new file mode 100644 index 000000000000..d690ea70cfa1 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/conftest.py @@ -0,0 +1,15 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from devtools_testutils import test_proxy, add_body_key_sanitizer +import pytest + +# autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method +@pytest.fixture(scope="session", autouse=True) +def start_proxy(test_proxy): + add_body_key_sanitizer(json_path="$..id_token", value="Sanitized") + add_body_key_sanitizer(json_path="$..client_info", value="Sanitized") + return \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_devcenter_operations.pyTestDevcentertest_devbox_operations.json b/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_devcenter_operations.pyTestDevcentertest_devbox_operations.json new file mode 100644 index 000000000000..8090234fb960 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_devcenter_operations.pyTestDevcentertest_devbox_operations.json @@ -0,0 +1,719 @@ +{ + "Entries": [ + { + "RequestUri": "https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-identity/1.11.0b4 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Allow-Origin": "*", + "Cache-Control": "max-age=86400, private", + "Content-Length": "1589", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:23:55 GMT", + "P3P": "CP=\u0022DSP CUR OTPi IND OTRi ONL FIN\u0022", + "Set-Cookie": [ + "fpc=ApueUMeYvB5IpeL0hfjMyIg; expires=Sun, 13-Nov-2022 21:23:55 GMT; path=/; secure; HttpOnly; SameSite=None", + "esctx=AQABAAAAAAD--DLA3VO7QrddgJg7WevrvVrVQrI_2Y947KiFQjINiJmHE-opaOHWvL9Rg3SZLJd7m42tvlZI_2Tkrv3N-O6B-eNuCrw0T_GDSeiw-ymxf-_fvqCO8KyKz30WfKzvMELpERnOxk__2S0k9batF_d5TGQRiuOmOPYWOKTowX2fUlOdlLgRXAKHMruV0U9wu8smm8K2olh0Z6zTJsFTD1Fobcn_IIxupm-elptrJX1xiFOi-nB0Xhcj1WfRqs3Io4IgAA; domain=.login.microsoftonline.com; path=/; secure; HttpOnly; SameSite=None", + "x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly", + "stsservicecookie=estsfd; path=/; secure; samesite=none; httponly" + ], + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", + "X-Content-Type-Options": "nosniff", + "x-ms-ests-server": "2.1.13777.6 - SCUS ProdSlices", + "X-XSS-Protection": "0" + }, + "ResponseBody": { + "token_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/token", + "token_endpoint_auth_methods_supported": [ + "client_secret_post", + "private_key_jwt", + "client_secret_basic" + ], + "jwks_uri": "https://login.microsoftonline.com/organizations/discovery/v2.0/keys", + "response_modes_supported": [ + "query", + "fragment", + "form_post" + ], + "subject_types_supported": [ + "pairwise" + ], + "id_token_signing_alg_values_supported": [ + "RS256" + ], + "response_types_supported": [ + "code", + "id_token", + "code id_token", + "id_token token" + ], + "scopes_supported": [ + "openid", + "profile", + "email", + "offline_access" + ], + "issuer": "https://login.microsoftonline.com/{tenantid}/v2.0", + "request_uri_parameter_supported": false, + "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", + "authorization_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize", + "device_authorization_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode", + "http_logout_supported": true, + "frontchannel_logout_supported": true, + "end_session_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/logout", + "claims_supported": [ + "sub", + "iss", + "cloud_instance_name", + "cloud_instance_host_name", + "cloud_graph_host_name", + "msgraph_host", + "aud", + "exp", + "iat", + "auth_time", + "acr", + "nonce", + "preferred_username", + "name", + "tid", + "ver", + "at_hash", + "c_hash", + "email" + ], + "kerberos_endpoint": "https://login.microsoftonline.com/organizations/kerberos", + "tenant_region_scope": null, + "cloud_instance_name": "microsoftonline.com", + "cloud_graph_host_name": "graph.windows.net", + "msgraph_host": "graph.microsoft.com", + "rbac_url": "https://pas.windows.net" + } + }, + { + "RequestUri": "https://login.microsoftonline.com/organizations/oauth2/v2.0/token", + "RequestMethod": "POST", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "client-request-id": "1c493f1a-10a8-4389-acf5-760974f852fa", + "Connection": "keep-alive", + "Content-Length": "1351", + "Content-Type": "application/x-www-form-urlencoded", + "Cookie": "fpc=ApueUMeYvB5IpeL0hfjMyIg; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd", + "User-Agent": "azsdk-python-identity/1.11.0b4 Python/3.10.6 (Windows-10-10.0.22000-SP0)", + "X-AnchorMailbox": "Oid:11111111-1111-1111-1111-111111111111@88888888-8888-8888-8888-888888888888", + "x-client-cpu": "x64", + "x-client-current-telemetry": "4|832,0|", + "x-client-last-telemetry": "4|0|||", + "x-client-os": "win32", + "x-client-sku": "MSAL.Python", + "x-client-ver": "1.19.0", + "x-ms-lib-capability": "retry-after, h429" + }, + "RequestBody": "client_id=04b07795-8ddb-461a-bbee-02f9e1bf7b46\u0026grant_type=authorization_code\u0026client_info=1\u0026claims=%7B%22access_token%22%3A\u002B%7B%22xms_cc%22%3A\u002B%7B%22values%22%3A\u002B%5B%22CP1%22%5D%7D%7D%7D\u0026code_verifier=Lj3qgx0MXRbQlsnZKHhGvPwaU6fTCV.k5EmWpIt-Bey\u0026code=0.ARoAHN-yiojtRkmoqeG7s-TR_ZV3sATbjRpGu-4C-eG_e0YaAHg.AgABAAIAAAD--DLA3VO7QrddgJg7WevrAgDs_wQA9P8Bwck8OmQ0Go2FbZe5nz9hxWS93mR7f1frEVsc2LaI87tFfT3tU5cGZZjmS8wSJM48i2AdrAjs3WinSCS7sLqcCXJyfJBbaz39WN-xwXo7D-AoBpF_nDdgmTf4ULdQq5RGssvmeteO3Hl07pttWu9G9DjBLrZJkJB00eyer81xLkukfoDJ7WK_Qm2WWxlPCYZy05zD6Wl-GntYUrZifDtrcV2cH3DP41JMcRrEGgX9CNzcO2hr9tu41slqmtMU0DwoVwEqP4kIwzAXD62shr8GCjvv0qjB28rCniNdzDaI37uny6_AC3FlTLbV33k1SwEhz2r5MvBF2QyLNNZ4y_-XQj7ZrVZOwcN4su7fJ4rQvoYizlLJhinhwSyi7OWt9koBSYTYVRCA1qgc0Dx7A5iN4tYEThTUu1riycV51yqAIAXYq2mmK5iZCObMFeZkEyO0mJRZwU-1OOcwvxZQeKStRNRo6cajAkXuuYcq2o-eU2aCWh6-jEbXHTfIE4d3dfyxghobVhBCetQ1fwJ711zMm6H3mI6wOhylp_JMgi44lfb4w6amnanbm_MazUoxztH6AbF-XJONLd_Do9-eIWsNty71gqqahLQBVKJXihJQ-SWL4dSnPV3iuX_FoNWdJ0cz8gJd2U45J9ujhXlByJUidn4hnbpOp2cZsA1cKVqeoePE4yqO7pdXazrBiahCne0YoCR2C9f6biTu85eTU0AHJZRl91RXmaqCoEwRJ_4A9oAi6shAjo5w9UHK02YBQ0wLGGxmPgmUvJDyXmnuHrGt2KM6ktt2EhhKR38tOTrxoMKUUANi46b3-sRuDi1aiV_Eeb14oPMX0-OjUfST0obe1-2C47xl8FrsviBAC0M3Sipe-fox\u0026redirect_uri=http%3A%2F%2Flocalhost%3A8400\u0026scope=https%3A%2F%2Fdevcenter.azure.com%2F.default\u002Boffline_access\u002Bopenid\u002Bprofile", + "StatusCode": 200, + "ResponseHeaders": { + "Cache-Control": "no-store, no-cache", + "client-request-id": "1c493f1a-10a8-4389-acf5-760974f852fa", + "Content-Length": "1768", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:24:30 GMT", + "Expires": "-1", + "P3P": "CP=\u0022DSP CUR OTPi IND OTRi ONL FIN\u0022", + "Pragma": "no-cache", + "Set-Cookie": [ + "fpc=ApueUMeYvB5IpeL0hfjMyIi7RtQJAQAAAI7K29oOAAAA; expires=Sun, 13-Nov-2022 21:24:31 GMT; path=/; secure; HttpOnly; SameSite=None", + "x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly", + "stsservicecookie=estsfd; path=/; secure; samesite=none; httponly" + ], + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", + "X-Content-Type-Options": "nosniff", + "x-ms-clitelem": "1,0,0,,", + "x-ms-ests-server": "2.1.13777.6 - NCUS ProdSlices", + "X-XSS-Protection": "0" + }, + "ResponseBody": { + "token_type": "Bearer", + "scope": "https://devcenter.azure.com/user_impersonation https://devcenter.azure.com/.default", + "expires_in": 3869, + "ext_expires_in": 3869, + "access_token": "Sanitized", + "refresh_token": "Sanitized", + "foci": "1", + "id_token": "Sanitized", + "client_info": "Sanitized" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/users/11111111-1111-1111-1111-111111111111/devboxes/Test_DevBox?api-version=2022-03-01-preview", + "RequestMethod": "PUT", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "Content-Length": "32", + "Content-Type": "application/json", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": { + "poolName": "sdk-default-pool" + }, + "StatusCode": 201, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "842", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:24:33 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "b1b3827e-140a-43ab-b3eb-7d535eb5a60a", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "297", + "X-Rate-Limit-Reset": "2022-10-14T21:25:09.5934413Z" + }, + "ResponseBody": { + "name": "Test_DevBox", + "projectName": "sdk-default-project", + "poolName": "sdk-default-pool", + "provisioningState": "Creating", + "actionState": "Unknown", + "uniqueId": "7e18fd68-fde0-452d-9d30-d1f063f0aa0c", + "location": "eastus", + "osType": "Windows", + "user": "11111111-1111-1111-1111-111111111111", + "hardwareProfile": { + "skuName": "general_a_8c32gb_v1", + "memoryGB": 32, + "vCPUs": 8 + }, + "storageProfile": { + "osDisk": { + "diskSizeGB": 1024 + } + }, + "imageReference": { + "name": "MicrosoftWindowsDesktop_windows-ent-cpc_win11-21h2-ent-cpc-m365", + "version": "1.0.0", + "operatingSystem": "Windows11", + "osBuildNumber": "win11-21h2-ent-cpc-m365", + "publishedDate": "2021-10-04T00:00:00\u002B00:00" + }, + "createdTime": "2022-10-14T21:24:31.7518165\u002B00:00", + "localAdministrator": "Enabled" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:25:03 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "ff1b48be-5c6b-436b-b8bc-9f5e89f65670", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T21:26:03.2886553Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Running", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:25:33 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "f69148f2-5e02-402a-8702-3430a09dfc33", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "297", + "X-Rate-Limit-Reset": "2022-10-14T21:25:46.2575770Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Running", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:32:37 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "687e74de-b61d-4c4a-bb8c-1746d5a03e68", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T21:33:37.2625250Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Running", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:33:07 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "272d7f9e-5a62-439b-a8a0-156d63b0bb4e", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T21:34:07.4351416Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Running", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:33:37 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "a013995f-0de1-4640-8a10-7eed02e6f1f9", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T21:34:37.5838454Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Running", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:34:08 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "5924d94a-7817-4ac3-bc38-130f59fec380", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T21:35:07.8985139Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Running", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:34:38 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "fabde91a-9a21-484a-959b-a3d22b829675", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "298", + "X-Rate-Limit-Reset": "2022-10-14T21:35:07.4201251Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Running", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Encoding": "gzip", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:55:18 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "Transfer-Encoding": "chunked", + "x-ms-correlation-request-id": "675c0397-a6b3-4f6d-87ca-00f6a86b6d42", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T21:56:17.2622978Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/e4686681-d55d-43c1-b72a-98970b925f27", + "name": "e4686681-d55d-43c1-b72a-98970b925f27", + "status": "Succeeded", + "startTime": "2022-10-14T21:24:32.0236552\u002B00:00", + "endTime": "2022-10-14T21:54:48.6309353\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/users/11111111-1111-1111-1111-111111111111/devboxes/Test_DevBox?api-version=2022-03-01-preview", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Encoding": "gzip", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:55:18 GMT", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "Transfer-Encoding": "chunked", + "x-ms-correlation-request-id": "f97c5174-f5d0-41da-9374-014faf8a2ffe", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T21:56:18.1137538Z" + }, + "ResponseBody": { + "name": "Test_DevBox", + "projectName": "sdk-default-project", + "poolName": "sdk-default-pool", + "provisioningState": "Succeeded", + "actionState": "Unknown", + "powerState": "Running", + "uniqueId": "7e18fd68-fde0-452d-9d30-d1f063f0aa0c", + "errorDetails": {}, + "location": "eastus", + "osType": "Windows", + "user": "11111111-1111-1111-1111-111111111111", + "hardwareProfile": { + "skuName": "general_a_8c32gb_v1", + "memoryGB": 32, + "vCPUs": 8 + }, + "storageProfile": { + "osDisk": { + "diskSizeGB": 1024 + } + }, + "imageReference": { + "name": "MicrosoftWindowsDesktop_windows-ent-cpc_win11-21h2-ent-cpc-m365", + "version": "1.0.0", + "operatingSystem": "Windows11", + "osBuildNumber": "win11-21h2-ent-cpc-m365", + "publishedDate": "2021-10-04T00:00:00\u002B00:00" + }, + "createdTime": "2022-10-14T21:24:31.7518165\u002B00:00", + "localAdministrator": "Enabled" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/users/me/devboxes/Test_DevBox?api-version=2022-03-01-preview", + "RequestMethod": "DELETE", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "Content-Length": "0", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 202, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "891", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:55:19 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "f2520048-b7aa-43b1-b821-a2fbda0d9a0a", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "298", + "X-Rate-Limit-Reset": "2022-10-14T21:55:47.0669914Z" + }, + "ResponseBody": { + "name": "Test_DevBox", + "projectName": "sdk-default-project", + "poolName": "sdk-default-pool", + "provisioningState": "Deleting", + "actionState": "Unknown", + "powerState": "Running", + "uniqueId": "7e18fd68-fde0-452d-9d30-d1f063f0aa0c", + "errorDetails": {}, + "location": "eastus", + "osType": "Windows", + "user": "11111111-1111-1111-1111-111111111111", + "hardwareProfile": { + "skuName": "general_a_8c32gb_v1", + "memoryGB": 32, + "vCPUs": 8 + }, + "storageProfile": { + "osDisk": { + "diskSizeGB": 1024 + } + }, + "imageReference": { + "name": "MicrosoftWindowsDesktop_windows-ent-cpc_win11-21h2-ent-cpc-m365", + "version": "1.0.0", + "operatingSystem": "Windows11", + "osBuildNumber": "win11-21h2-ent-cpc-m365", + "publishedDate": "2021-10-04T00:00:00\u002B00:00" + }, + "createdTime": "2022-10-14T21:24:31.7518165\u002B00:00", + "localAdministrator": "Enabled" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:55:49 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "397a7fdc-144a-4709-81c0-1541e41d9e66", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "298", + "X-Rate-Limit-Reset": "2022-10-14T21:56:17.2622978Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "name": "57f6054f-c996-4799-bdc3-aeba35d5369c", + "status": "Running", + "startTime": "2022-10-14T21:55:18.4249831\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:56:19 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "14719614-f672-4e1d-9f35-da2d020ede5f", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "298", + "X-Rate-Limit-Reset": "2022-10-14T21:57:16.3045613Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "name": "57f6054f-c996-4799-bdc3-aeba35d5369c", + "status": "Running", + "startTime": "2022-10-14T21:55:18.4249831\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 21:56:49 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "1c8aa4e2-41a1-46df-865e-38464c1b16a7", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "298", + "X-Rate-Limit-Reset": "2022-10-14T21:57:31.5301354Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "name": "57f6054f-c996-4799-bdc3-aeba35d5369c", + "status": "Running", + "startTime": "2022-10-14T21:55:18.4249831\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Encoding": "gzip", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 14 Oct 2022 22:02:23 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "Transfer-Encoding": "chunked", + "x-ms-correlation-request-id": "459ba321-d3d3-4ebc-a44b-18a19e55fb91", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-14T22:03:22.9387752Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/57f6054f-c996-4799-bdc3-aeba35d5369c", + "name": "57f6054f-c996-4799-bdc3-aeba35d5369c", + "status": "Succeeded", + "startTime": "2022-10-14T21:55:18.4249831\u002B00:00", + "endTime": "2022-10-14T22:02:13.5259436\u002B00:00" + } + } + ], + "Variables": {} +} diff --git a/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_devcenter_operations.pyTestDevcentertest_environment_operations.json b/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_devcenter_operations.pyTestDevcentertest_environment_operations.json new file mode 100644 index 000000000000..77caef2aea21 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_devcenter_operations.pyTestDevcentertest_environment_operations.json @@ -0,0 +1,456 @@ +{ + "Entries": [ + { + "RequestUri": "https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-identity/1.11.0b4 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Allow-Origin": "*", + "Cache-Control": "max-age=86400, private", + "Content-Length": "1589", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:56:35 GMT", + "P3P": "CP=\u0022DSP CUR OTPi IND OTRi ONL FIN\u0022", + "Set-Cookie": [ + "fpc=Ar5Hpmre3bJDin73axo8N_c; expires=Mon, 14-Nov-2022 00:56:36 GMT; path=/; secure; HttpOnly; SameSite=None", + "esctx=AQABAAAAAAD--DLA3VO7QrddgJg7WevrSeDo_IkbNN-6bq5fdU0Ra7V-hmXsPBdh784G7oSlH8LZ0qB-w0TpiqLwygCWxzi18nl41O-t2prrsO4cOMwi0-Tkvvir9_8WxSkScZ13liqyL_0oNEUb9_6AnFut-F-qfJN66iAPtUH7-4LxRh1AXbM3S3GF5Jd7ci7ToauCgWFXqBCKxh8xRoOdbsCRhwHrvtBKAki3FbAi5virGU20Ct1i_0w61oaQevMZpJxw98wgAA; domain=.login.microsoftonline.com; path=/; secure; HttpOnly; SameSite=None", + "x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly", + "stsservicecookie=estsfd; path=/; secure; samesite=none; httponly" + ], + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", + "X-Content-Type-Options": "nosniff", + "x-ms-ests-server": "2.1.13777.6 - WUS2 ProdSlices", + "X-XSS-Protection": "0" + }, + "ResponseBody": { + "token_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/token", + "token_endpoint_auth_methods_supported": [ + "client_secret_post", + "private_key_jwt", + "client_secret_basic" + ], + "jwks_uri": "https://login.microsoftonline.com/organizations/discovery/v2.0/keys", + "response_modes_supported": [ + "query", + "fragment", + "form_post" + ], + "subject_types_supported": [ + "pairwise" + ], + "id_token_signing_alg_values_supported": [ + "RS256" + ], + "response_types_supported": [ + "code", + "id_token", + "code id_token", + "id_token token" + ], + "scopes_supported": [ + "openid", + "profile", + "email", + "offline_access" + ], + "issuer": "https://login.microsoftonline.com/{tenantid}/v2.0", + "request_uri_parameter_supported": false, + "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", + "authorization_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize", + "device_authorization_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode", + "http_logout_supported": true, + "frontchannel_logout_supported": true, + "end_session_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/logout", + "claims_supported": [ + "sub", + "iss", + "cloud_instance_name", + "cloud_instance_host_name", + "cloud_graph_host_name", + "msgraph_host", + "aud", + "exp", + "iat", + "auth_time", + "acr", + "nonce", + "preferred_username", + "name", + "tid", + "ver", + "at_hash", + "c_hash", + "email" + ], + "kerberos_endpoint": "https://login.microsoftonline.com/organizations/kerberos", + "tenant_region_scope": null, + "cloud_instance_name": "microsoftonline.com", + "cloud_graph_host_name": "graph.windows.net", + "msgraph_host": "graph.microsoft.com", + "rbac_url": "https://pas.windows.net" + } + }, + { + "RequestUri": "https://login.microsoftonline.com/organizations/oauth2/v2.0/token", + "RequestMethod": "POST", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "client-request-id": "3a13687d-2f19-4e88-bdbb-b06a8565fd1f", + "Connection": "keep-alive", + "Content-Length": "1349", + "Content-Type": "application/x-www-form-urlencoded", + "Cookie": "fpc=Ar5Hpmre3bJDin73axo8N_c; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd", + "User-Agent": "azsdk-python-identity/1.11.0b4 Python/3.10.6 (Windows-10-10.0.22000-SP0)", + "X-AnchorMailbox": "Oid:11111111-1111-1111-1111-111111111111@88888888-8888-8888-8888-888888888888", + "x-client-cpu": "x64", + "x-client-current-telemetry": "4|832,0|", + "x-client-last-telemetry": "4|0|||", + "x-client-os": "win32", + "x-client-sku": "MSAL.Python", + "x-client-ver": "1.19.0", + "x-ms-lib-capability": "retry-after, h429" + }, + "RequestBody": "client_id=04b07795-8ddb-461a-bbee-02f9e1bf7b46\u0026grant_type=authorization_code\u0026client_info=1\u0026claims=%7B%22access_token%22%3A\u002B%7B%22xms_cc%22%3A\u002B%7B%22values%22%3A\u002B%5B%22CP1%22%5D%7D%7D%7D\u0026code_verifier=ykDQreY2C5-j.1c3WTmRFGHwSg7sbqLf~PJIo6lVvB4\u0026code=0.ARoAHN-yiojtRkmoqeG7s-TR_ZV3sATbjRpGu-4C-eG_e0YaAHg.AgABAAIAAAD--DLA3VO7QrddgJg7WevrAgDs_wQA9P8U5A-LiC7fdkwfoMKlezOXfzUHRDgTVKXm6ZvIpVowaAFlfwxVnKHVdVUVdx6SMAF2pH3ZK7MFCrGOQDPQ0Jm22OPniU-EiYEKaLH_FC8vlh-PrAGg0p7n8WMndet0icrX4HvaN0vxpUpSfBzIMb8cKDxX60lvMuE0Hk-0t8FPE1CE194MTTwq6SYszbPrJXzsPC6LPoAe0KJZuDj1rNscI3XFcRTkR7CtOJVRZ40DillFZYgJ0_hWWEkLw_wKi1gyh5ViegNT3ajYPynAEhB9a3KxGZhtS1JCkbKU1JxkWJ1sBtbl3GlduvRwpK5KMq6JfTs7Hfn9z0NeqsgQcHRkczSuGMSKclCw062c-1k3SobBhZfZ_J0l2nAZ987-MzfCQhEBpyOtFeohPSjFtQwMRhNZlEQo6LNoD88Rs15cA7OIpm8SKeXVQ0hEpnsHI4kOJgSDTjzjKCEfVzigNFQ_Nq4UfKW_U0J1nZMYXO5neU4Ho1jb74c8RdDkEfZ-HbPPGtWgHTluJFQDSDWohl5qjyIBfdKbsDGXmX3sveoF-mf4i3UDF_cbXWbY351zTvvvySxQeY8xnWk6zNlwQ8N7sqhP2U-2vcUUkTyGhyD1WNp64rphiSoH7mzi96rrO1S2olvzrbKbtz-AGgJAbhPI_kxGShCDKtP3JXpdBbU8cqbenkAeZhgkWqnqmCmkcoCMbQplOZbWqSdtF41__7IZnEEpuvYvHrKmjJ7kNGu8i77ZupSOKDfx6MgGCfMBiUV8fau9JIjtx_Hq5gWlC_oUo2NWFlfrKqF8Ggy8BhULX53lI8uhfJA_p_ggT6UkeB17GohB88yYTo6Mz3rhf0NSvFeDi_Gnd_VRO8bPg4BvhdbZwQ\u0026redirect_uri=http%3A%2F%2Flocalhost%3A8400\u0026scope=https%3A%2F%2Fdevcenter.azure.com%2F.default\u002Boffline_access\u002Bopenid\u002Bprofile", + "StatusCode": 200, + "ResponseHeaders": { + "Cache-Control": "no-store, no-cache", + "client-request-id": "3a13687d-2f19-4e88-bdbb-b06a8565fd1f", + "Content-Length": "1768", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:56:39 GMT", + "Expires": "-1", + "P3P": "CP=\u0022DSP CUR OTPi IND OTRi ONL FIN\u0022", + "Pragma": "no-cache", + "Set-Cookie": [ + "fpc=Ar5Hpmre3bJDin73axo8N_e7RtQJAQAAAEb829oOAAAA; expires=Mon, 14-Nov-2022 00:56:39 GMT; path=/; secure; HttpOnly; SameSite=None", + "x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly", + "stsservicecookie=estsfd; path=/; secure; samesite=none; httponly" + ], + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", + "X-Content-Type-Options": "nosniff", + "x-ms-clitelem": "1,0,0,,", + "x-ms-ests-server": "2.1.13777.6 - WUS2 ProdSlices", + "X-XSS-Protection": "0" + }, + "ResponseBody": { + "token_type": "Bearer", + "scope": "https://devcenter.azure.com/user_impersonation https://devcenter.azure.com/.default", + "expires_in": 3991, + "ext_expires_in": 3991, + "access_token": "Sanitized", + "refresh_token": "Sanitized", + "foci": "1", + "id_token": "Sanitized", + "client_info": "Sanitized" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/users/me/environments/Dev_Environment?api-version=2022-03-01-preview", + "RequestMethod": "PUT", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "Content-Length": "117", + "Content-Type": "application/json", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": { + "catalogItemName": "Empty", + "environmentType": "sdk-default-environment-type", + "catalogName": "sdk-default-catalog" + }, + "StatusCode": 201, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "278", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:56:40 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "845370a8-91e1-4994-ae9b-5f7c43f49c75", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-15T00:57:40.1593263Z" + }, + "ResponseBody": { + "name": "dev_environment", + "environmentType": "sdk-default-environment-type", + "owner": "11111111-1111-1111-1111-111111111111", + "provisioningState": "Creating", + "catalogName": "sdk-default-catalog", + "catalogItemName": "Empty", + "scheduledTasks": {}, + "tags": {} + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:57:10 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "31eae88a-8e93-4f30-a1cc-24485d0edb54", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "297", + "X-Rate-Limit-Reset": "2022-10-15T00:57:17.0936909Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/a4724537-e334-4238-b045-575122db1269", + "name": "a4724537-e334-4238-b045-575122db1269", + "status": "Running", + "startTime": "2022-10-15T00:56:40.5959861\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:58:41 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "69cfb27e-1d69-490b-b578-c4f0c9783a83", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-15T00:59:41.4243655Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/a4724537-e334-4238-b045-575122db1269", + "name": "a4724537-e334-4238-b045-575122db1269", + "status": "Running", + "startTime": "2022-10-15T00:56:40.5959861\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Encoding": "gzip", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:59:11 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/a4724537-e334-4238-b045-575122db1269", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "Transfer-Encoding": "chunked", + "x-ms-correlation-request-id": "f0f5632e-645a-4b6c-85a3-eac2de457ffe", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-15T01:00:11.5745262Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/a4724537-e334-4238-b045-575122db1269", + "name": "a4724537-e334-4238-b045-575122db1269", + "status": "Succeeded", + "startTime": "2022-10-15T00:56:40.5959861\u002B00:00", + "endTime": "2022-10-15T00:59:00.5672928\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/users/me/environments/Dev_Environment?api-version=2022-03-01-preview", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Encoding": "gzip", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:59:11 GMT", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "Transfer-Encoding": "chunked", + "x-ms-correlation-request-id": "fa05ce98-c15c-424d-9c88-94da590261ac", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-15T01:00:11.7387646Z" + }, + "ResponseBody": { + "name": "dev_environment", + "environmentType": "sdk-default-environment-type", + "owner": "11111111-1111-1111-1111-111111111111", + "provisioningState": "Succeeded", + "resourceGroupId": "/subscriptions/62e47139-66d0-4b0b-a000-1e8a412890c1/resourceGroups/sdk-default-project-dev_environment", + "catalogName": "sdk-default-catalog", + "catalogItemName": "Empty", + "scheduledTasks": {}, + "tags": {} + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/users/me/environments/Dev_Environment?api-version=2022-03-01-preview", + "RequestMethod": "DELETE", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "Content-Length": "0", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 202, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "0", + "Date": "Sat, 15 Oct 2022 00:59:12 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "da356bcb-cb32-41cd-a983-332e76e20600", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "298", + "X-Rate-Limit-Reset": "2022-10-15T00:59:41.4243655Z" + }, + "ResponseBody": null + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 00:59:42 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "4d36a373-1fec-441d-9e26-b7d8c6067020", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "297", + "X-Rate-Limit-Reset": "2022-10-15T01:00:11.5745262Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "name": "4dc29d9b-db1e-440f-891f-22afd24ffee4", + "status": "Running", + "startTime": "2022-10-15T00:59:12.1930569\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Length": "223", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 01:00:12 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "x-ms-correlation-request-id": "852f7618-74d0-4a4d-859b-bb917846e701", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "299", + "X-Rate-Limit-Reset": "2022-10-15T01:01:12.5806034Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "name": "4dc29d9b-db1e-440f-891f-22afd24ffee4", + "status": "Running", + "startTime": "2022-10-15T00:59:12.1930569\u002B00:00" + } + }, + { + "RequestUri": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "User-Agent": "azsdk-python-developer-devcenter/1.0.0b1 Python/3.10.6 (Windows-10-10.0.22000-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Connection": "keep-alive", + "Content-Encoding": "gzip", + "Content-Type": "application/json; charset=utf-8", + "Date": "Sat, 15 Oct 2022 01:00:42 GMT", + "Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4?monitor=true", + "Operation-Location": "https://88888888-8888-8888-8888-888888888888-sdk-default-dc.devcenter.azure.com/projects/sdk-default-project/operationstatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "retry-after": "1", + "Strict-Transport-Security": "max-age=15724800; includeSubDomains", + "Transfer-Encoding": "chunked", + "x-ms-correlation-request-id": "3682b899-7dac-4788-be06-f5f28f492ab8", + "X-Rate-Limit-Limit": "1m", + "X-Rate-Limit-Remaining": "297", + "X-Rate-Limit-Reset": "2022-10-15T01:01:17.0956399Z" + }, + "ResponseBody": { + "id": "/projects/sdk-default-project/operationStatuses/4dc29d9b-db1e-440f-891f-22afd24ffee4", + "name": "4dc29d9b-db1e-440f-891f-22afd24ffee4", + "status": "Succeeded", + "startTime": "2022-10-15T00:59:12.1930569\u002B00:00", + "endTime": "2022-10-15T01:00:20.2137046\u002B00:00" + } + } + ], + "Variables": {} +} diff --git a/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_smoke.pyTestDevcenterSmoketest_smoke.json b/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_smoke.pyTestDevcenterSmoketest_smoke.json new file mode 100644 index 000000000000..f721723386d8 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/recordings/test_smoke.pyTestDevcenterSmoketest_smoke.json @@ -0,0 +1,4 @@ +{ + "Entries": [], + "Variables": {} +} diff --git a/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations.py b/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations.py new file mode 100644 index 000000000000..9951e956b804 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/test_devcenter_operations.py @@ -0,0 +1,79 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import functools +import os +import pytest +import logging +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer, recorded_by_proxy +from azure.identity import InteractiveBrowserCredential +from azure.developer.devcenter import DevCenterClient +from azure.core.exceptions import HttpResponseError +from testcase import DevcenterPowerShellPreparer + +class TestDevcenter(AzureRecordedTestCase): + def create_client(self, dev_center_name, devcenter_tenant_id): + credential = self.get_credential(DevCenterClient) + return DevCenterClient( + devcenter_tenant_id, + dev_center_name, + credential=credential + ) + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_devbox_operations(self, **kwargs): + self.logger = logging.getLogger(__name__) + devcenter_name = kwargs.pop("devcenter_name") + azure_tenant_id = kwargs.pop("devcenter_tenant_id") + default_project_name = kwargs.pop("devcenter_project_name") + default_pool_name = kwargs.pop("devcenter_pool_name") + static_test_user_id = kwargs.pop("devcenter_test_user_id") + + client = self.create_client(devcenter_name, azure_tenant_id) + + # Fetch control plane resource dependencies + + # Stand up a new dev box + create_response = client.dev_boxes.begin_create_dev_box(default_project_name, "Test_DevBox", {"poolName": default_pool_name}, user_id=static_test_user_id) + devbox_result = create_response.result() + + self.logger.info(f"Provisioned dev box with status {devbox_result['provisioningState']}.") + assert devbox_result['provisioningState'] in ["Succeeded", "ProvisionedWithWarning"] + + # Tear down the dev box + delete_response = client.dev_boxes.begin_delete_dev_box(default_project_name, "Test_DevBox") + delete_response.wait() + self.logger.info("Completed deletion for the dev box.") + + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_environment_operations(self, **kwargs): + self.logger = logging.getLogger(__name__) + devcenter_name = kwargs.pop("devcenter_name") + azure_tenant_id = kwargs.pop("devcenter_tenant_id") + default_project_name = kwargs.pop("devcenter_project_name") + default_environment_type_name = kwargs.pop("devcenter_environment_type_name") + default_catalog_name = kwargs.pop("devcenter_catalog_name") + default_catalog_item_name = kwargs.pop("devcenter_catalog_item_name") + + client = self.create_client(devcenter_name, azure_tenant_id) + + # Fetch control plane resource dependencies + create_response = client.environments.begin_create_or_update_environment(default_project_name, + "Dev_Environment", + {"catalogItemName": default_catalog_item_name, + "environmentType": default_environment_type_name, + "catalogName": default_catalog_name}) + environment_result = create_response.result() + + self.logger.info(f"Provisioned environment with status {environment_result['provisioningState']}.") + assert environment_result['provisioningState'] == "Succeeded" + + # Tear down the environment when finished + delete_response = client.environments.begin_delete_environment(default_project_name, "Dev_Environment") + delete_response.wait() + self.logger.info("Completed deletion for the environment.") \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/tests/test_smoke.py b/sdk/devcenter/azure-developer-devcenter/tests/test_smoke.py new file mode 100644 index 000000000000..98f87c1ef5f3 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/test_smoke.py @@ -0,0 +1,18 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import os +from testcase import DevcenterTest, DevcenterPowerShellPreparer +from devtools_testutils import recorded_by_proxy + +class TestDevcenterSmoke(DevcenterTest): + @DevcenterPowerShellPreparer() + @recorded_by_proxy + def test_smoke(self, **kwargs): + azure_tenant_id = kwargs.pop("devcenter_tenant_id") + devcenter_name = kwargs.pop("devcenter_name") + client = self.create_client(tenant_id=azure_tenant_id, dev_center=devcenter_name) + assert client is not None diff --git a/sdk/devcenter/azure-developer-devcenter/tests/testcase.py b/sdk/devcenter/azure-developer-devcenter/tests/testcase.py new file mode 100644 index 000000000000..b617ffe5324e --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/testcase.py @@ -0,0 +1,32 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +import functools +from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, PowerShellPreparer +from azure.developer.devcenter import DevCenterClient + + +class DevcenterTest(AzureRecordedTestCase): + def create_client(self, tenant_id, dev_center): + credential = self.get_credential(DevCenterClient) + return DevCenterClient( + dev_center=dev_center, + tenant_id=tenant_id, + credential=credential + ) + +DevcenterPowerShellPreparer = functools.partial( + PowerShellPreparer, + "devcenter", + devcenter_name="sdk-default-dc", + devcenter_tenant_id="88888888-8888-8888-8888-888888888888", + devcenter_project_name="sdk-default-project", + devcenter_pool_name="sdk-default-pool", + devcenter_test_user_id="11111111-1111-1111-1111-111111111111", + devcenter_environment_type_name="sdk-default-environment-type", + devcenter_catalog_name="sdk-default-catalog", + devcenter_catalog_item_name="Empty") \ No newline at end of file diff --git a/sdk/devcenter/azure-developer-devcenter/tests/testcase_async.py b/sdk/devcenter/azure-developer-devcenter/tests/testcase_async.py new file mode 100644 index 000000000000..377659324524 --- /dev/null +++ b/sdk/devcenter/azure-developer-devcenter/tests/testcase_async.py @@ -0,0 +1,18 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from devtools_testutils import AzureTestCase +from azure.developer.devcenter.aio import DevCenterClient + + +class DevcenterAsyncTest(AzureTestCase): + def create_client(self, tenant_id, dev_center): + credential = self.get_credential(DevCenterClient) + return DevCenterClient( + dev_center=dev_center, + tenant_id=tenant_id, + credential=credential + ) diff --git a/sdk/devcenter/ci.yml b/sdk/devcenter/ci.yml index ced4aab0ae80..56dc516a1375 100644 --- a/sdk/devcenter/ci.yml +++ b/sdk/devcenter/ci.yml @@ -28,6 +28,9 @@ extends: template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml parameters: ServiceDirectory: devcenter + TestProxy: true Artifacts: - name: azure-mgmt-devcenter safeName: azuremgmtdevcenter + - name: azure-developer-devcenter + safeName: azuredeveloperdevcenter diff --git a/shared_requirements.txt b/shared_requirements.txt index b77d16d25d82..9c98d6074efa 100644 --- a/shared_requirements.txt +++ b/shared_requirements.txt @@ -532,4 +532,6 @@ opentelemetry-sdk<2.0.0,>=1.5.0,!=1.10a0 #override azure-mgmt-redis azure-mgmt-core>=1.3.2,<2.0.0 #override azure-mgmt-resourcegraph azure-mgmt-core>=1.3.2,<2.0.0 #override azure-mgmt-resourcegraph msrest>=0.7.1 -#override azure-core-experimental azure-core<2.0.0,>=1.25.0 \ No newline at end of file +#override azure-core-experimental azure-core<2.0.0,>=1.25.0 +#override azure-developer-devcenter isodate<1.0.0,>=0.6.1 +#override azure-developer-devcenter azure-core<2.0.0,>=1.24.0 \ No newline at end of file