From 04c0e16688026a5995e60ab67c30429dc0ea438d Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Thu, 13 Jun 2024 08:15:17 +0000 Subject: [PATCH] CodeGen from PR 29427 in Azure/azure-rest-api-specs Merge 0403d481fb49f7e2ecc9c0a27434fffd66b35763 into 1996b293669d94f9817d42fd72b1eae7fa320b57 --- .../azure-mgmt-computefleet/CHANGELOG.md | 5 + .../azure-mgmt-computefleet/LICENSE | 21 + .../azure-mgmt-computefleet/MANIFEST.in | 8 + .../azure-mgmt-computefleet/README.md | 61 + .../azure-mgmt-computefleet/_meta.json | 11 + .../azure-mgmt-computefleet/azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/computefleet/__init__.py | 26 + .../azure/mgmt/computefleet/_configuration.py | 65 + .../computefleet/_microsoft_azure_fleet.py | 120 + .../azure/mgmt/computefleet/_patch.py | 20 + .../azure/mgmt/computefleet/_serialization.py | 1998 +++++++ .../azure/mgmt/computefleet/_vendor.py | 16 + .../azure/mgmt/computefleet/_version.py | 9 + .../azure/mgmt/computefleet/aio/__init__.py | 23 + .../mgmt/computefleet/aio/_configuration.py | 65 + .../aio/_microsoft_azure_fleet.py | 122 + .../azure/mgmt/computefleet/aio/_patch.py | 20 + .../computefleet/aio/operations/__init__.py | 23 + .../aio/operations/_fleets_operations.py | 767 +++ .../aio/operations/_operations.py | 134 + .../computefleet/aio/operations/_patch.py | 20 + .../_virtual_machine_scale_sets_operations.py | 146 + .../mgmt/computefleet/models/__init__.py | 269 + .../models/_microsoft_azure_fleet_enums.py | 413 ++ .../mgmt/computefleet/models/_models_py3.py | 4849 +++++++++++++++++ .../azure/mgmt/computefleet/models/_patch.py | 20 + .../mgmt/computefleet/operations/__init__.py | 23 + .../operations/_fleets_operations.py | 947 ++++ .../computefleet/operations/_operations.py | 156 + .../mgmt/computefleet/operations/_patch.py | 20 + .../_virtual_machine_scale_sets_operations.py | 181 + .../azure/mgmt/computefleet/py.typed | 1 + .../fleets_create_or_update.py | 340 ++ .../generated_samples/fleets_delete.py | 41 + .../generated_samples/fleets_get.py | 42 + .../fleets_list_by_resource_group.py | 42 + .../fleets_list_by_subscription.py | 40 + .../generated_samples/fleets_update.py | 345 ++ .../generated_samples/operations_list.py | 40 + ...irtual_machine_scale_sets_list_by_fleet.py | 43 + .../sdk_packaging.toml | 11 + .../azure-mgmt-computefleet/setup.py | 82 + sdk/computefleet/ci.yml | 34 + .../azure-mgmt-mongocluster/CHANGELOG.md | 5 + .../azure-mgmt-mongocluster/LICENSE | 21 + .../azure-mgmt-mongocluster/MANIFEST.in | 8 + .../azure-mgmt-mongocluster/README.md | 61 + .../azure-mgmt-mongocluster/_meta.json | 11 + .../azure-mgmt-mongocluster/azure/__init__.py | 1 + .../azure/mgmt/__init__.py | 1 + .../azure/mgmt/mongocluster/__init__.py | 26 + .../azure/mgmt/mongocluster/_configuration.py | 65 + .../_mongo_cluster_management_client.py | 133 + .../azure/mgmt/mongocluster/_patch.py | 20 + .../azure/mgmt/mongocluster/_serialization.py | 1998 +++++++ .../azure/mgmt/mongocluster/_vendor.py | 16 + .../azure/mgmt/mongocluster/_version.py | 9 + .../azure/mgmt/mongocluster/aio/__init__.py | 23 + .../mgmt/mongocluster/aio/_configuration.py | 65 + .../aio/_mongo_cluster_management_client.py | 135 + .../azure/mgmt/mongocluster/aio/_patch.py | 20 + .../mongocluster/aio/operations/__init__.py | 27 + .../operations/_firewall_rules_operations.py | 536 ++ .../operations/_mongo_clusters_operations.py | 962 ++++ .../aio/operations/_operations.py | 134 + .../mongocluster/aio/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 546 ++ .../operations/_private_links_operations.py | 145 + .../mgmt/mongocluster/models/__init__.py | 107 + .../mgmt/mongocluster/models/_models_py3.py | 1449 +++++ .../_mongo_cluster_management_client_enums.py | 122 + .../azure/mgmt/mongocluster/models/_patch.py | 20 + .../mgmt/mongocluster/operations/__init__.py | 27 + .../operations/_firewall_rules_operations.py | 719 +++ .../operations/_mongo_clusters_operations.py | 1243 +++++ .../mongocluster/operations/_operations.py | 156 + .../mgmt/mongocluster/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 726 +++ .../operations/_private_links_operations.py | 187 + .../azure/mgmt/mongocluster/py.typed | 1 + .../mongo_clusters_create.py | 55 + .../mongo_clusters_create_pitr.py | 54 + .../mongo_clusters_delete.py | 41 + .../mongo_clusters_firewall_rule_create.py | 46 + .../mongo_clusters_firewall_rule_delete.py | 42 + .../mongo_clusters_firewall_rule_get.py | 43 + .../mongo_clusters_firewall_rule_list.py | 43 + .../generated_samples/mongo_clusters_get.py | 42 + .../generated_samples/mongo_clusters_list.py | 40 + .../mongo_clusters_list_by_resource_group.py | 42 + .../mongo_clusters_list_connection_strings.py | 42 + .../mongo_clusters_name_availability.py | 44 + ...usters_name_availability_already_exists.py | 44 + .../mongo_clusters_patch_disk_size.py | 45 + ...o_clusters_patch_private_network_access.py | 45 + ...ters_private_endpoint_connection_delete.py | 42 + ...lusters_private_endpoint_connection_get.py | 43 + ...usters_private_endpoint_connection_list.py | 43 + ...lusters_private_endpoint_connection_put.py | 48 + ...ngo_clusters_private_link_resource_list.py | 43 + .../mongo_clusters_update.py | 55 + .../generated_samples/operations_list.py | 40 + .../sdk_packaging.toml | 11 + .../azure-mgmt-mongocluster/setup.py | 82 + sdk/mongocluster/ci.yml | 34 + 106 files changed, 22495 insertions(+) create mode 100644 sdk/computefleet/azure-mgmt-computefleet/CHANGELOG.md create mode 100644 sdk/computefleet/azure-mgmt-computefleet/LICENSE create mode 100644 sdk/computefleet/azure-mgmt-computefleet/MANIFEST.in create mode 100644 sdk/computefleet/azure-mgmt-computefleet/README.md create mode 100644 sdk/computefleet/azure-mgmt-computefleet/_meta.json create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/__init__.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/__init__.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/__init__.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_configuration.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_microsoft_azure_fleet.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_patch.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_serialization.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_vendor.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_version.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/__init__.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_configuration.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_microsoft_azure_fleet.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_patch.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/__init__.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_fleets_operations.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_operations.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_patch.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_virtual_machine_scale_sets_operations.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/__init__.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_microsoft_azure_fleet_enums.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_models_py3.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_patch.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/__init__.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_fleets_operations.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_operations.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_patch.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_virtual_machine_scale_sets_operations.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/py.typed create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_create_or_update.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_delete.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_get.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_resource_group.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_subscription.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_update.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/operations_list.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/generated_samples/virtual_machine_scale_sets_list_by_fleet.py create mode 100644 sdk/computefleet/azure-mgmt-computefleet/sdk_packaging.toml create mode 100644 sdk/computefleet/azure-mgmt-computefleet/setup.py create mode 100644 sdk/computefleet/ci.yml create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/CHANGELOG.md create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/LICENSE create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/MANIFEST.in create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/README.md create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/_meta.json create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/__init__.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/__init__.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/__init__.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_configuration.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_mongo_cluster_management_client.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_patch.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_serialization.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_vendor.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_version.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/__init__.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_configuration.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_mongo_cluster_management_client.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_patch.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/__init__.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_firewall_rules_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_mongo_clusters_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_patch.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_endpoint_connections_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_links_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/__init__.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_models_py3.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_mongo_cluster_management_client_enums.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_patch.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/__init__.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_firewall_rules_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_mongo_clusters_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_patch.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_endpoint_connections_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_links_operations.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/py.typed create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create_pitr.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_delete.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_create.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_delete.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_get.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_list.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_get.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_by_resource_group.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_connection_strings.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability_already_exists.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_disk_size.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_private_network_access.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_delete.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_get.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_list.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_put.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_link_resource_list.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_update.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/operations_list.py create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/sdk_packaging.toml create mode 100644 sdk/mongocluster/azure-mgmt-mongocluster/setup.py create mode 100644 sdk/mongocluster/ci.yml diff --git a/sdk/computefleet/azure-mgmt-computefleet/CHANGELOG.md b/sdk/computefleet/azure-mgmt-computefleet/CHANGELOG.md new file mode 100644 index 000000000000..578ed6acf479 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 0.1.0 (1970-01-01) + +* Initial Release diff --git a/sdk/computefleet/azure-mgmt-computefleet/LICENSE b/sdk/computefleet/azure-mgmt-computefleet/LICENSE new file mode 100644 index 000000000000..b2f52a2bad4e --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/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. diff --git a/sdk/computefleet/azure-mgmt-computefleet/MANIFEST.in b/sdk/computefleet/azure-mgmt-computefleet/MANIFEST.in new file mode 100644 index 000000000000..604d3c94efff --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/MANIFEST.in @@ -0,0 +1,8 @@ +include _meta.json +recursive-include tests *.py *.json +recursive-include samples *.py *.md +include *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include LICENSE +include azure/mgmt/computefleet/py.typed diff --git a/sdk/computefleet/azure-mgmt-computefleet/README.md b/sdk/computefleet/azure-mgmt-computefleet/README.md new file mode 100644 index 000000000000..585eef55356e --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure MyService Management Client Library. +This package has been tested with Python 3.8+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.8+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-computefleet +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configure of following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.computefleet import +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = (credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search MyService Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/computefleet/azure-mgmt-computefleet/_meta.json b/sdk/computefleet/azure-mgmt-computefleet/_meta.json new file mode 100644 index 000000000000..db6cbe261ec7 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/_meta.json @@ -0,0 +1,11 @@ +{ + "commit": "293ac41c07fad031af73b7290797c6c3e784d8ac", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.13.19", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/azurefleet/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.13.19 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/azurefleet/resource-manager/readme.md" +} \ No newline at end of file diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/__init__.py b/sdk/computefleet/azure-mgmt-computefleet/azure/__init__.py new file mode 100644 index 000000000000..8db66d3d0f0f --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/__init__.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/__init__.py new file mode 100644 index 000000000000..8db66d3d0f0f --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/__init__.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/__init__.py new file mode 100644 index 000000000000..f55041cdcb36 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/__init__.py @@ -0,0 +1,26 @@ +# 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 ._microsoft_azure_fleet import MicrosoftAzureFleet +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "MicrosoftAzureFleet", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_configuration.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_configuration.py new file mode 100644 index 000000000000..649e7aa2d1fd --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_configuration.py @@ -0,0 +1,65 @@ +# 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.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MicrosoftAzureFleetConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for MicrosoftAzureFleet. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2024-05-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-05-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-computefleet/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_microsoft_azure_fleet.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_microsoft_azure_fleet.py new file mode 100644 index 000000000000..d0d9a622b8d7 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_microsoft_azure_fleet.py @@ -0,0 +1,120 @@ +# 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.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy + +from . import models as _models +from ._configuration import MicrosoftAzureFleetConfiguration +from ._serialization import Deserializer, Serializer +from .operations import FleetsOperations, Operations, VirtualMachineScaleSetsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MicrosoftAzureFleet: # pylint: disable=client-accepts-api-version-keyword + """MicrosoftAzureFleet. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.computefleet.operations.Operations + :ivar fleets: FleetsOperations operations + :vartype fleets: azure.mgmt.computefleet.operations.FleetsOperations + :ivar virtual_machine_scale_sets: VirtualMachineScaleSetsOperations operations + :vartype virtual_machine_scale_sets: + azure.mgmt.computefleet.operations.VirtualMachineScaleSetsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2024-05-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, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MicrosoftAzureFleetConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.fleets = FleetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_machine_scale_sets = VirtualMachineScaleSetsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **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) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "MicrosoftAzureFleet": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_patch.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_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/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_serialization.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_serialization.py new file mode 100644 index 000000000000..f0c6180722c8 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_serialization.py @@ -0,0 +1,1998 @@ +# -------------------------------------------------------------------------- +# +# 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 +# pyright: reportUnnecessaryTypeIgnoreComment=false + +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 +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] + + +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: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> 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 as err: + # 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 DeserializationError("XML is invalid") from err + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: 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 + + +_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 # type: ignore +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 +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[Dict[str, Any]] = {} + for k in kwargs: + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node.""" + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result.update(objects[valuetype]._flatten_subtype(key, objects)) + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + Remove the polymorphic key from the initial data. + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + """ + return key.replace("\\.", ".") + + +class Serializer(object): + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > 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: Optional[Mapping[str, type]] = 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[str, type] = 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) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + 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) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from 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_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, 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 = [ # type: ignore + 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 SerializationError("Unable to build a model: " + str(err)) from 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) + output = output.replace("{", quote("{")).replace("}", quote("}")) + 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. + :keyword bool skip_quote: Whether to skip quote the serialized result. + Defaults to False. + :rtype: str, list + :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] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **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 is CoreNull: + return None + 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 SerializationError(msg.format(data, data_type)) from 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): # type: ignore + # 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'. + :keyword bool do_quote: Whether to quote the serialized result of each iterable element. + Defaults to False. + :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 as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + 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 as err: + if isinstance(err, SerializationError): + raise + 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 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) # type: ignore + return result + except ValueError: + for enum_value in enum_obj: # type: ignore + 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 SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from 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: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _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 + 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 + 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: Optional[Mapping[str, type]] = 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[str, type] = 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, str): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore + 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 # type: ignore + raise DeserializationError(msg) from 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 deserialize. + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + 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 deserialize. + :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, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + 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) # type: ignore + 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 DeserializationError(msg) from 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, str): + 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, str): + 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): # type: ignore + 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. + 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)) # type: ignore + + @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) # type: ignore + attr = attr + padding # type: ignore + 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(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from 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) # type: ignore + + @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 DeserializationError(msg) from 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): # type: ignore + 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=0, defaultday=0) + + @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): # type: ignore + 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) # type: ignore + 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 DeserializationError(msg) from 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() # type: ignore + 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 DeserializationError(msg) from 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) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + else: + return date_obj diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_vendor.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_vendor.py new file mode 100644 index 000000000000..0dafe0e287ff --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_vendor.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_version.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/_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/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/__init__.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/__init__.py new file mode 100644 index 000000000000..251982f3fb49 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/__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 ._microsoft_azure_fleet import MicrosoftAzureFleet + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "MicrosoftAzureFleet", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_configuration.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_configuration.py new file mode 100644 index 000000000000..5dfdeb9c4b5a --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_configuration.py @@ -0,0 +1,65 @@ +# 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.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MicrosoftAzureFleetConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for MicrosoftAzureFleet. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2024-05-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-05-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-computefleet/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_microsoft_azure_fleet.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_microsoft_azure_fleet.py new file mode 100644 index 000000000000..cf757f186e0a --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_microsoft_azure_fleet.py @@ -0,0 +1,122 @@ +# 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.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy + +from .. import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import MicrosoftAzureFleetConfiguration +from .operations import FleetsOperations, Operations, VirtualMachineScaleSetsOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MicrosoftAzureFleet: # pylint: disable=client-accepts-api-version-keyword + """MicrosoftAzureFleet. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.computefleet.aio.operations.Operations + :ivar fleets: FleetsOperations operations + :vartype fleets: azure.mgmt.computefleet.aio.operations.FleetsOperations + :ivar virtual_machine_scale_sets: VirtualMachineScaleSetsOperations operations + :vartype virtual_machine_scale_sets: + azure.mgmt.computefleet.aio.operations.VirtualMachineScaleSetsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2024-05-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, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MicrosoftAzureFleetConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.fleets = FleetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.virtual_machine_scale_sets = VirtualMachineScaleSetsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **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) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MicrosoftAzureFleet": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_patch.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/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/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/__init__.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/__init__.py new file mode 100644 index 000000000000..11d54761c024 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/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 Operations +from ._fleets_operations import FleetsOperations +from ._virtual_machine_scale_sets_operations import VirtualMachineScaleSetsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "FleetsOperations", + "VirtualMachineScaleSetsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_fleets_operations.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_fleets_operations.py new file mode 100644 index 000000000000..2b66d7b69ec9 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_fleets_operations.py @@ -0,0 +1,767 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._fleets_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_by_subscription_request, + build_update_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class FleetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.computefleet.aio.MicrosoftAzureFleet`'s + :attr:`fleets` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Fleet"]: + """List Fleet resources by subscription ID. + + :return: An iterator like instance of either Fleet or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FleetListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FleetListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Fleet"]: + """List Fleet resources by resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either Fleet or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FleetListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FleetListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, resource_group_name: str, fleet_name: str, **kwargs: Any) -> _models.Fleet: + """Get a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :return: Fleet or the result of cls(response) + :rtype: ~azure.mgmt.computefleet.models.Fleet + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Fleet", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, resource_group_name: str, fleet_name: str, resource: Union[_models.Fleet, IO[bytes]], **kwargs: Any + ) -> _models.Fleet: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "Fleet") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("Fleet", pipeline_response) + + if response.status_code == 201: + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = self._deserialize("Fleet", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + fleet_name: str, + resource: _models.Fleet, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Fleet]: + """Create a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.computefleet.models.Fleet + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + fleet_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Fleet]: + """Create a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, resource_group_name: str, fleet_name: str, resource: Union[_models.Fleet, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[_models.Fleet]: + """Create a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param resource: Resource create parameters. Is either a Fleet type or a IO[bytes] type. + Required. + :type resource: ~azure.mgmt.computefleet.models.Fleet or IO[bytes] + :return: An instance of AsyncLROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Fleet", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.Fleet].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.Fleet]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + resource_group_name: str, + fleet_name: str, + properties: Union[_models.FleetUpdate, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.Fleet]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.Fleet]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "FleetUpdate") + + _request = build_update_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("Fleet", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + fleet_name: str, + properties: _models.FleetUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Fleet]: + """Update a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.computefleet.models.FleetUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + fleet_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Fleet]: + """Update a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + fleet_name: str, + properties: Union[_models.FleetUpdate, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.Fleet]: + """Update a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param properties: The resource properties to be updated. Is either a FleetUpdate type or a + IO[bytes] type. Required. + :type properties: ~azure.mgmt.computefleet.models.FleetUpdate or IO[bytes] + :return: An instance of AsyncLROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + properties=properties, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Fleet", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.Fleet].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.Fleet]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, fleet_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def begin_delete(self, resource_group_name: str, fleet_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Delete a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + fleet_name=fleet_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_operations.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_operations.py new file mode 100644 index 000000000000..19aa50aff549 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_operations.py @@ -0,0 +1,134 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.computefleet.aio.MicrosoftAzureFleet`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.computefleet.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_patch.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/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/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_virtual_machine_scale_sets_operations.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_virtual_machine_scale_sets_operations.py new file mode 100644 index 000000000000..81652d379e1b --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/aio/operations/_virtual_machine_scale_sets_operations.py @@ -0,0 +1,146 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._virtual_machine_scale_sets_operations import build_list_by_fleet_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class VirtualMachineScaleSetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.computefleet.aio.MicrosoftAzureFleet`'s + :attr:`virtual_machine_scale_sets` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_fleet( + self, resource_group_name: str, name: str, **kwargs: Any + ) -> AsyncIterable["_models.VirtualMachineScaleSet"]: + """List VirtualMachineScaleSet resources by Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the Fleet. Required. + :type name: str + :return: An iterator like instance of either VirtualMachineScaleSet or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.computefleet.models.VirtualMachineScaleSet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.VirtualMachineScaleSetListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_fleet_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("VirtualMachineScaleSetListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/__init__.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/__init__.py new file mode 100644 index 000000000000..6865adc61873 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/__init__.py @@ -0,0 +1,269 @@ +# 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 ._models_py3 import AdditionalUnattendContent +from ._models_py3 import ApiEntityReference +from ._models_py3 import ApiError +from ._models_py3 import ApiErrorBase +from ._models_py3 import ApplicationProfile +from ._models_py3 import BasePriorityProfile +from ._models_py3 import BillingProfile +from ._models_py3 import BootDiagnostics +from ._models_py3 import CapacityReservationProfile +from ._models_py3 import ComputeProfile +from ._models_py3 import ComputeProfileUpdate +from ._models_py3 import DiagnosticsProfile +from ._models_py3 import DiffDiskSettings +from ._models_py3 import DiskEncryptionSetParameters +from ._models_py3 import EncryptionIdentity +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import Fleet +from ._models_py3 import FleetListResult +from ._models_py3 import FleetPropertiesUpdate +from ._models_py3 import FleetUpdate +from ._models_py3 import ImageReference +from ._models_py3 import InnerError +from ._models_py3 import InstanceViewStatus +from ._models_py3 import KeyVaultSecretReference +from ._models_py3 import LinuxConfiguration +from ._models_py3 import LinuxPatchSettings +from ._models_py3 import LinuxVMGuestPatchAutomaticByPlatformSettings +from ._models_py3 import ManagedServiceIdentity +from ._models_py3 import ManagedServiceIdentityUpdate +from ._models_py3 import OSImageNotificationProfile +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import PatchSettings +from ._models_py3 import Plan +from ._models_py3 import ProxyAgentSettings +from ._models_py3 import PublicIPAddressSku +from ._models_py3 import RegularPriorityProfile +from ._models_py3 import Resource +from ._models_py3 import ResourcePlanUpdate +from ._models_py3 import ResourceWithOptionalLocation +from ._models_py3 import ScheduledEventsProfile +from ._models_py3 import SecurityPostureReference +from ._models_py3 import SecurityProfile +from ._models_py3 import ServiceArtifactReference +from ._models_py3 import SpotPriorityProfile +from ._models_py3 import SshConfiguration +from ._models_py3 import SshPublicKey +from ._models_py3 import SubResource +from ._models_py3 import SubResourceReadOnly +from ._models_py3 import SystemData +from ._models_py3 import TerminateNotificationProfile +from ._models_py3 import TrackedResource +from ._models_py3 import UefiSettings +from ._models_py3 import UserAssignedIdentity +from ._models_py3 import VMDiskSecurityProfile +from ._models_py3 import VMGalleryApplication +from ._models_py3 import VMSizeProperties +from ._models_py3 import VaultCertificate +from ._models_py3 import VaultSecretGroup +from ._models_py3 import VirtualHardDisk +from ._models_py3 import VirtualMachineExtension +from ._models_py3 import VirtualMachineExtensionInstanceView +from ._models_py3 import VirtualMachineScaleSet +from ._models_py3 import VirtualMachineScaleSetDataDisk +from ._models_py3 import VirtualMachineScaleSetExtension +from ._models_py3 import VirtualMachineScaleSetExtensionProfile +from ._models_py3 import VirtualMachineScaleSetHardwareProfile +from ._models_py3 import VirtualMachineScaleSetIPConfiguration +from ._models_py3 import VirtualMachineScaleSetIpTag +from ._models_py3 import VirtualMachineScaleSetListResult +from ._models_py3 import VirtualMachineScaleSetManagedDiskParameters +from ._models_py3 import VirtualMachineScaleSetNetworkConfiguration +from ._models_py3 import VirtualMachineScaleSetNetworkConfigurationDnsSettings +from ._models_py3 import VirtualMachineScaleSetNetworkProfile +from ._models_py3 import VirtualMachineScaleSetOSDisk +from ._models_py3 import VirtualMachineScaleSetOSProfile +from ._models_py3 import VirtualMachineScaleSetPublicIPAddressConfiguration +from ._models_py3 import VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings +from ._models_py3 import VirtualMachineScaleSetStorageProfile +from ._models_py3 import VirtualMachineScaleSetVMProfile +from ._models_py3 import VmSizeProfile +from ._models_py3 import WinRMConfiguration +from ._models_py3 import WinRMListener +from ._models_py3 import WindowsConfiguration +from ._models_py3 import WindowsVMGuestPatchAutomaticByPlatformSettings + +from ._microsoft_azure_fleet_enums import ActionType +from ._microsoft_azure_fleet_enums import CachingTypes +from ._microsoft_azure_fleet_enums import CreatedByType +from ._microsoft_azure_fleet_enums import DeleteOptions +from ._microsoft_azure_fleet_enums import DiffDiskOptions +from ._microsoft_azure_fleet_enums import DiffDiskPlacement +from ._microsoft_azure_fleet_enums import DiskControllerTypes +from ._microsoft_azure_fleet_enums import DiskCreateOptionTypes +from ._microsoft_azure_fleet_enums import DiskDeleteOptionTypes +from ._microsoft_azure_fleet_enums import DomainNameLabelScopeTypes +from ._microsoft_azure_fleet_enums import EvictionPolicy +from ._microsoft_azure_fleet_enums import IPVersion +from ._microsoft_azure_fleet_enums import LinuxPatchAssessmentMode +from ._microsoft_azure_fleet_enums import LinuxVMGuestPatchAutomaticByPlatformRebootSetting +from ._microsoft_azure_fleet_enums import LinuxVMGuestPatchMode +from ._microsoft_azure_fleet_enums import ManagedServiceIdentityType +from ._microsoft_azure_fleet_enums import Mode +from ._microsoft_azure_fleet_enums import NetworkApiVersion +from ._microsoft_azure_fleet_enums import NetworkInterfaceAuxiliaryMode +from ._microsoft_azure_fleet_enums import NetworkInterfaceAuxiliarySku +from ._microsoft_azure_fleet_enums import OperatingSystemTypes +from ._microsoft_azure_fleet_enums import Origin +from ._microsoft_azure_fleet_enums import ProtocolTypes +from ._microsoft_azure_fleet_enums import ProvisioningState +from ._microsoft_azure_fleet_enums import PublicIPAddressSkuName +from ._microsoft_azure_fleet_enums import PublicIPAddressSkuTier +from ._microsoft_azure_fleet_enums import RegularPriorityAllocationStrategy +from ._microsoft_azure_fleet_enums import SecurityEncryptionTypes +from ._microsoft_azure_fleet_enums import SecurityTypes +from ._microsoft_azure_fleet_enums import SettingNames +from ._microsoft_azure_fleet_enums import SpotAllocationStrategy +from ._microsoft_azure_fleet_enums import StatusLevelTypes +from ._microsoft_azure_fleet_enums import StorageAccountTypes +from ._microsoft_azure_fleet_enums import VirtualMachineEvictionPolicyTypes +from ._microsoft_azure_fleet_enums import VirtualMachinePriorityTypes +from ._microsoft_azure_fleet_enums import WindowsPatchAssessmentMode +from ._microsoft_azure_fleet_enums import WindowsVMGuestPatchAutomaticByPlatformRebootSetting +from ._microsoft_azure_fleet_enums import WindowsVMGuestPatchMode +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AdditionalUnattendContent", + "ApiEntityReference", + "ApiError", + "ApiErrorBase", + "ApplicationProfile", + "BasePriorityProfile", + "BillingProfile", + "BootDiagnostics", + "CapacityReservationProfile", + "ComputeProfile", + "ComputeProfileUpdate", + "DiagnosticsProfile", + "DiffDiskSettings", + "DiskEncryptionSetParameters", + "EncryptionIdentity", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "Fleet", + "FleetListResult", + "FleetPropertiesUpdate", + "FleetUpdate", + "ImageReference", + "InnerError", + "InstanceViewStatus", + "KeyVaultSecretReference", + "LinuxConfiguration", + "LinuxPatchSettings", + "LinuxVMGuestPatchAutomaticByPlatformSettings", + "ManagedServiceIdentity", + "ManagedServiceIdentityUpdate", + "OSImageNotificationProfile", + "Operation", + "OperationDisplay", + "OperationListResult", + "PatchSettings", + "Plan", + "ProxyAgentSettings", + "PublicIPAddressSku", + "RegularPriorityProfile", + "Resource", + "ResourcePlanUpdate", + "ResourceWithOptionalLocation", + "ScheduledEventsProfile", + "SecurityPostureReference", + "SecurityProfile", + "ServiceArtifactReference", + "SpotPriorityProfile", + "SshConfiguration", + "SshPublicKey", + "SubResource", + "SubResourceReadOnly", + "SystemData", + "TerminateNotificationProfile", + "TrackedResource", + "UefiSettings", + "UserAssignedIdentity", + "VMDiskSecurityProfile", + "VMGalleryApplication", + "VMSizeProperties", + "VaultCertificate", + "VaultSecretGroup", + "VirtualHardDisk", + "VirtualMachineExtension", + "VirtualMachineExtensionInstanceView", + "VirtualMachineScaleSet", + "VirtualMachineScaleSetDataDisk", + "VirtualMachineScaleSetExtension", + "VirtualMachineScaleSetExtensionProfile", + "VirtualMachineScaleSetHardwareProfile", + "VirtualMachineScaleSetIPConfiguration", + "VirtualMachineScaleSetIpTag", + "VirtualMachineScaleSetListResult", + "VirtualMachineScaleSetManagedDiskParameters", + "VirtualMachineScaleSetNetworkConfiguration", + "VirtualMachineScaleSetNetworkConfigurationDnsSettings", + "VirtualMachineScaleSetNetworkProfile", + "VirtualMachineScaleSetOSDisk", + "VirtualMachineScaleSetOSProfile", + "VirtualMachineScaleSetPublicIPAddressConfiguration", + "VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings", + "VirtualMachineScaleSetStorageProfile", + "VirtualMachineScaleSetVMProfile", + "VmSizeProfile", + "WinRMConfiguration", + "WinRMListener", + "WindowsConfiguration", + "WindowsVMGuestPatchAutomaticByPlatformSettings", + "ActionType", + "CachingTypes", + "CreatedByType", + "DeleteOptions", + "DiffDiskOptions", + "DiffDiskPlacement", + "DiskControllerTypes", + "DiskCreateOptionTypes", + "DiskDeleteOptionTypes", + "DomainNameLabelScopeTypes", + "EvictionPolicy", + "IPVersion", + "LinuxPatchAssessmentMode", + "LinuxVMGuestPatchAutomaticByPlatformRebootSetting", + "LinuxVMGuestPatchMode", + "ManagedServiceIdentityType", + "Mode", + "NetworkApiVersion", + "NetworkInterfaceAuxiliaryMode", + "NetworkInterfaceAuxiliarySku", + "OperatingSystemTypes", + "Origin", + "ProtocolTypes", + "ProvisioningState", + "PublicIPAddressSkuName", + "PublicIPAddressSkuTier", + "RegularPriorityAllocationStrategy", + "SecurityEncryptionTypes", + "SecurityTypes", + "SettingNames", + "SpotAllocationStrategy", + "StatusLevelTypes", + "StorageAccountTypes", + "VirtualMachineEvictionPolicyTypes", + "VirtualMachinePriorityTypes", + "WindowsPatchAssessmentMode", + "WindowsVMGuestPatchAutomaticByPlatformRebootSetting", + "WindowsVMGuestPatchMode", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_microsoft_azure_fleet_enums.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_microsoft_azure_fleet_enums.py new file mode 100644 index 000000000000..99c54cb59b2b --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_microsoft_azure_fleet_enums.py @@ -0,0 +1,413 @@ +# 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 enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" + + INTERNAL = "Internal" + + +class CachingTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the caching requirements. Possible values are: **None,** **ReadOnly,** **ReadWrite.** + The default values are: **None for Standard storage. ReadOnly for Premium storage**. + """ + + NONE = "None" + READ_ONLY = "ReadOnly" + READ_WRITE = "ReadWrite" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class DeleteOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specify what happens to the network interface when the VM is deleted.""" + + DELETE = "Delete" + DETACH = "Detach" + + +class DiffDiskOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the ephemeral disk option for operating system disk.""" + + LOCAL = "Local" + + +class DiffDiskPlacement(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the ephemeral disk placement for operating system disk. This property can be used by + user in the request to choose the location i.e, cache disk or resource disk space for Ephemeral + OS disk provisioning. For more information on Ephemeral OS disk size requirements, please refer + Ephemeral OS disk size requirements for Windows VM at + https://docs.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements + and Linux VM at + https://docs.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. + """ + + CACHE_DISK = "CacheDisk" + RESOURCE_DISK = "ResourceDisk" + + +class DiskControllerTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the disk controller type configured for the VM and VirtualMachineScaleSet. This + property is only supported for virtual machines whose operating system disk and VM sku supports + Generation 2 (https://docs.microsoft.com/en-us/azure/virtual-machines/generation-2), please + check the HyperVGenerations capability returned as part of VM sku capabilities in the response + of Microsoft.Compute SKUs api for the region contains V2 + (https://docs.microsoft.com/rest/api/compute/resourceskus/list). For more information about + Disk Controller Types supported please refer to https://aka.ms/azure-diskcontrollertypes. + """ + + SCSI = "SCSI" + NV_ME = "NVMe" + + +class DiskCreateOptionTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies how the virtual machine should be created. Possible values are: **Attach.** This + value is used when you are using a specialized disk to create the virtual machine. + **FromImage.** This value is used when you are using an image to create the virtual machine. If + you are using a platform image, you also use the imageReference element described above. If you + are using a marketplace image, you also use the plan element previously described. + """ + + FROM_IMAGE = "FromImage" + EMPTY = "Empty" + ATTACH = "Attach" + + +class DiskDeleteOptionTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the behavior of the managed disk when the VM gets deleted, for example whether the + managed disk is deleted or detached. Supported values are: **Delete.** If this value is used, + the managed disk is deleted when VM gets deleted. **Detach.** If this value is used, the + managed disk is retained after VM gets deleted. Minimum api-version: 2021-03-01. + """ + + DELETE = "Delete" + DETACH = "Detach" + + +class DomainNameLabelScopeTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The Domain name label scope.The concatenation of the hashed domain name label that generated + according to the policy from domain name label scope and vm index will be the domain name + labels of the PublicIPAddress resources that will be created. + """ + + TENANT_REUSE = "TenantReuse" + SUBSCRIPTION_REUSE = "SubscriptionReuse" + RESOURCE_GROUP_REUSE = "ResourceGroupReuse" + NO_REUSE = "NoReuse" + + +class EvictionPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Different kind of eviction policies.""" + + DELETE = "Delete" + """When evicted, the Spot VM will be deleted and the corresponding capacity will be updated to + reflect this.""" + DEALLOCATE = "Deallocate" + """When evicted, the Spot VM will be deallocated/stopped""" + + +class IPVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Available from Api-Version 2017-03-30 onwards, it represents whether the specific + ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and + 'IPv6'. + """ + + I_PV4 = "IPv4" + I_PV6 = "IPv6" + + +class LinuxPatchAssessmentMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` **ImageDefault** - You + control the timing of patch assessments on a virtual machine. :code:`
`:code:`
` + **AutomaticByPlatform** - The platform will trigger periodic patch assessments. The property + provisionVMAgent must be true. + """ + + IMAGE_DEFAULT = "ImageDefault" + AUTOMATIC_BY_PLATFORM = "AutomaticByPlatform" + + +class LinuxVMGuestPatchAutomaticByPlatformRebootSetting(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the reboot setting for all AutomaticByPlatform patch installation operations.""" + + UNKNOWN = "Unknown" + IF_REQUIRED = "IfRequired" + NEVER = "Never" + ALWAYS = "Always" + + +class LinuxVMGuestPatchMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated + to virtual machine scale set with OrchestrationMode as Flexible.:code:`
`:code:`
` + Possible values are::code:`
`:code:`
` **ImageDefault** - The virtual machine's + default patching configuration is used. :code:`
`:code:`
` **AutomaticByPlatform** - + The virtual machine will be automatically updated by the platform. The property + provisionVMAgent must be true. + """ + + IMAGE_DEFAULT = "ImageDefault" + AUTOMATIC_BY_PLATFORM = "AutomaticByPlatform" + + +class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of managed service identity (where both SystemAssigned and UserAssigned types are + allowed). + """ + + NONE = "None" + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned,UserAssigned" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" + + +class Mode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the mode that ProxyAgent will execute on if the feature is enabled. ProxyAgent will + start to audit or monitor but not enforce access control over requests to host endpoints in + Audit mode, while in Enforce mode it will enforce access control. The default value is Enforce + mode. + """ + + AUDIT = "Audit" + ENFORCE = "Enforce" + + +class NetworkApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """specifies the Microsoft.Network API version used when creating networking resources in the + Network Interface Configurations for Virtual Machine Scale Set with orchestration mode + 'Flexible'. + """ + + TWO_THOUSAND_TWENTY11_01 = "2020-11-01" + + +class NetworkInterfaceAuxiliaryMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies whether the Auxiliary mode is enabled for the Network Interface resource.""" + + NONE = "None" + ACCELERATED_CONNECTIONS = "AcceleratedConnections" + FLOATING = "Floating" + + +class NetworkInterfaceAuxiliarySku(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies whether the Auxiliary sku is enabled for the Network Interface resource.""" + + NONE = "None" + A1 = "A1" + A2 = "A2" + A4 = "A4" + A8 = "A8" + + +class OperatingSystemTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """This property allows you to specify the type of the OS that is included in the disk if creating + a VM from user-image or a specialized VHD. Possible values are: **Windows,** **Linux.**. + """ + + WINDOWS = "Windows" + LINUX = "Linux" + + +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is "user,system". + """ + + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" + + +class ProtocolTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the protocol of WinRM listener. Possible values are: **http,** **https.**.""" + + HTTP = "Http" + HTTPS = "Https" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the current operation.""" + + SUCCEEDED = "Succeeded" + """Resource has been created.""" + FAILED = "Failed" + """Resource creation failed.""" + CANCELED = "Canceled" + """Resource creation was canceled.""" + CREATING = "Creating" + """Initial creation in progress.""" + UPDATING = "Updating" + """Update in progress.""" + DELETING = "Deleting" + """Deletion in progress.""" + MIGRATING = "Migrating" + """Resource is being migrated from one subscription or resource group to another.""" + + +class PublicIPAddressSkuName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specify public IP sku name.""" + + BASIC = "Basic" + STANDARD = "Standard" + + +class PublicIPAddressSkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specify public IP sku tier.""" + + REGIONAL = "Regional" + GLOBAL_ENUM = "Global" + + +class RegularPriorityAllocationStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Regular VM Allocation strategy types for Compute Fleet.""" + + LOWEST_PRICE = "LowestPrice" + """Default. VM sizes distribution will be determined to optimize for price.""" + PRIORITIZED = "Prioritized" + """VM sizes distribution will be determined to optimize for the 'priority' as specified for each + vm size.""" + + +class SecurityEncryptionTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for + encryption of the managed disk along with VMGuestState blob, VMGuestStateOnly for encryption of + just the VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the + VMGuestState blob.. **Note:** It can be set for only Confidential VMs. + """ + + VM_GUEST_STATE_ONLY = "VMGuestStateOnly" + DISK_WITH_VM_GUEST_STATE = "DiskWithVMGuestState" + NON_PERSISTED_TPM = "NonPersistedTPM" + + +class SecurityTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the SecurityType of the virtual machine. It has to be set to any specified value to + enable UefiSettings. The default behavior is: UefiSettings will not be enabled unless this + property is set. + """ + + TRUSTED_LAUNCH = "TrustedLaunch" + CONFIDENTIAL_VM = "ConfidentialVM" + + +class SettingNames(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the name of the setting to which the content applies. Possible values are: + FirstLogonCommands and AutoLogon. + """ + + AUTO_LOGON = "AutoLogon" + FIRST_LOGON_COMMANDS = "FirstLogonCommands" + + +class SpotAllocationStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Spot allocation strategy types for Compute Fleet.""" + + PRICE_CAPACITY_OPTIMIZED = "PriceCapacityOptimized" + """Default. VM sizes distribution will be determined to optimize for both price and capacity.""" + LOWEST_PRICE = "LowestPrice" + """VM sizes distribution will be determined to optimize for price. Note: Capacity will still be + considered here but will be given much less weight.""" + CAPACITY_OPTIMIZED = "CapacityOptimized" + """VM sizes distribution will be determined to optimize for capacity.""" + + +class StatusLevelTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The level code.""" + + INFO = "Info" + WARNING = "Warning" + ERROR = "Error" + + +class StorageAccountTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the storage account type for the managed disk. Managed OS disk storage account type + can only be set when you create the scale set. NOTE: UltraSSD_LRS can only be used with data + disks. It cannot be used with OS Disk. Standard_LRS uses Standard HDD. StandardSSD_LRS uses + Standard SSD. Premium_LRS uses Premium SSD. UltraSSD_LRS uses Ultra disk. Premium_ZRS uses + Premium SSD zone redundant storage. StandardSSD_ZRS uses Standard SSD zone redundant storage. + For more information regarding disks supported for Windows Virtual Machines, refer to + https://docs.microsoft.com/azure/virtual-machines/windows/disks-types and, for Linux Virtual + Machines, refer to https://docs.microsoft.com/azure/virtual-machines/linux/disks-types. + """ + + STANDARD_LRS = "Standard_LRS" + PREMIUM_LRS = "Premium_LRS" + STANDARD_SSD_LRS = "StandardSSD_LRS" + ULTRA_SSD_LRS = "UltraSSD_LRS" + PREMIUM_ZRS = "Premium_ZRS" + STANDARD_SSD_ZRS = "StandardSSD_ZRS" + PREMIUM_V2_LRS = "PremiumV2_LRS" + + +class VirtualMachineEvictionPolicyTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the eviction policy for the Azure Spot VM/VMSS.""" + + DEALLOCATE = "Deallocate" + DELETE = "Delete" + + +class VirtualMachinePriorityTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the priority for a standalone virtual machine or the virtual machines in the scale + set. 'Low' enum will be deprecated in the future, please use 'Spot' as the enum to deploy Azure + Spot VM/VMSS. + """ + + REGULAR = "Regular" + LOW = "Low" + SPOT = "Spot" + + +class WindowsPatchAssessmentMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the mode of VM Guest patch assessment for the IaaS virtual machine.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` **ImageDefault** - You + control the timing of patch assessments on a virtual machine.:code:`
`:code:`
` + **AutomaticByPlatform** - The platform will trigger periodic patch assessments. The property + provisionVMAgent must be true. + """ + + IMAGE_DEFAULT = "ImageDefault" + AUTOMATIC_BY_PLATFORM = "AutomaticByPlatform" + + +class WindowsVMGuestPatchAutomaticByPlatformRebootSetting(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the reboot setting for all AutomaticByPlatform patch installation operations.""" + + UNKNOWN = "Unknown" + IF_REQUIRED = "IfRequired" + NEVER = "Never" + ALWAYS = "Always" + + +class WindowsVMGuestPatchMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated + to virtual machine scale set with OrchestrationMode as Flexible.:code:`
`:code:`
` + Possible values are::code:`
`:code:`
` **Manual** - You control the application of + patches to a virtual machine. You do this by applying patches manually inside the VM. In this + mode, automatic updates are disabled; the property WindowsConfiguration.enableAutomaticUpdates + must be false:code:`
`:code:`
` **AutomaticByOS** - The virtual machine will + automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates + must be true. :code:`
`:code:`
` **AutomaticByPlatform** - the virtual machine will + automatically updated by the platform. The properties provisionVMAgent and + WindowsConfiguration.enableAutomaticUpdates must be true. + """ + + MANUAL = "Manual" + AUTOMATIC_BY_OS = "AutomaticByOS" + AUTOMATIC_BY_PLATFORM = "AutomaticByPlatform" diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_models_py3.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_models_py3.py new file mode 100644 index 000000000000..4f0217a173cd --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_models_py3.py @@ -0,0 +1,4849 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +import sys +from typing import Any, Dict, List, Literal, Optional, TYPE_CHECKING, Union + +from .. import _serialization + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class AdditionalUnattendContent(_serialization.Model): + """Specifies additional XML formatted information that can be included in the Unattend.xml file, + which is used by Windows Setup. Contents are defined by setting name, component name, and the + pass in which the content is applied. + + :ivar pass_name: The pass name. Currently, the only allowable value is OobeSystem. Default + value is "OobeSystem". + :vartype pass_name: str + :ivar component_name: The component name. Currently, the only allowable value is + Microsoft-Windows-Shell-Setup. Default value is "Microsoft-Windows-Shell-Setup". + :vartype component_name: str + :ivar setting_name: Specifies the name of the setting to which the content applies. Possible + values are: FirstLogonCommands and AutoLogon. Known values are: "AutoLogon" and + "FirstLogonCommands". + :vartype setting_name: str or ~azure.mgmt.computefleet.models.SettingNames + :ivar content: Specifies the XML formatted content that is added to the unattend.xml file for + the specified path and component. The XML must be less than 4KB and must include the root + element for the setting or feature that is being inserted. + :vartype content: str + """ + + _attribute_map = { + "pass_name": {"key": "passName", "type": "str"}, + "component_name": {"key": "componentName", "type": "str"}, + "setting_name": {"key": "settingName", "type": "str"}, + "content": {"key": "content", "type": "str"}, + } + + def __init__( + self, + *, + pass_name: Optional[Literal["OobeSystem"]] = None, + component_name: Optional[Literal["Microsoft-Windows-Shell-Setup"]] = None, + setting_name: Optional[Union[str, "_models.SettingNames"]] = None, + content: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword pass_name: The pass name. Currently, the only allowable value is OobeSystem. Default + value is "OobeSystem". + :paramtype pass_name: str + :keyword component_name: The component name. Currently, the only allowable value is + Microsoft-Windows-Shell-Setup. Default value is "Microsoft-Windows-Shell-Setup". + :paramtype component_name: str + :keyword setting_name: Specifies the name of the setting to which the content applies. Possible + values are: FirstLogonCommands and AutoLogon. Known values are: "AutoLogon" and + "FirstLogonCommands". + :paramtype setting_name: str or ~azure.mgmt.computefleet.models.SettingNames + :keyword content: Specifies the XML formatted content that is added to the unattend.xml file + for the specified path and component. The XML must be less than 4KB and must include the root + element for the setting or feature that is being inserted. + :paramtype content: str + """ + super().__init__(**kwargs) + self.pass_name = pass_name + self.component_name = component_name + self.setting_name = setting_name + self.content = content + + +class ApiEntityReference(_serialization.Model): + """The API entity reference. + + :ivar id: The ARM resource id in the form of + /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... + :vartype id: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: The ARM resource id in the form of + /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class ApiError(_serialization.Model): + """Api error. + + :ivar details: The Api error details. + :vartype details: list[~azure.mgmt.computefleet.models.ApiErrorBase] + :ivar innererror: The Api inner error. + :vartype innererror: ~azure.mgmt.computefleet.models.InnerError + :ivar code: The error code. + :vartype code: str + :ivar target: The target of the particular error. + :vartype target: str + :ivar message: The error message. + :vartype message: str + """ + + _attribute_map = { + "details": {"key": "details", "type": "[ApiErrorBase]"}, + "innererror": {"key": "innererror", "type": "InnerError"}, + "code": {"key": "code", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__( + self, + *, + details: Optional[List["_models.ApiErrorBase"]] = None, + innererror: Optional["_models.InnerError"] = None, + code: Optional[str] = None, + target: Optional[str] = None, + message: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword details: The Api error details. + :paramtype details: list[~azure.mgmt.computefleet.models.ApiErrorBase] + :keyword innererror: The Api inner error. + :paramtype innererror: ~azure.mgmt.computefleet.models.InnerError + :keyword code: The error code. + :paramtype code: str + :keyword target: The target of the particular error. + :paramtype target: str + :keyword message: The error message. + :paramtype message: str + """ + super().__init__(**kwargs) + self.details = details + self.innererror = innererror + self.code = code + self.target = target + self.message = message + + +class ApiErrorBase(_serialization.Model): + """Api error base. + + :ivar code: The error code. + :vartype code: str + :ivar target: The target of the particular error. + :vartype target: str + :ivar message: The error message. + :vartype message: str + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__( + self, *, code: Optional[str] = None, target: Optional[str] = None, message: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword code: The error code. + :paramtype code: str + :keyword target: The target of the particular error. + :paramtype target: str + :keyword message: The error message. + :paramtype message: str + """ + super().__init__(**kwargs) + self.code = code + self.target = target + self.message = message + + +class ApplicationProfile(_serialization.Model): + """Contains the list of gallery applications that should be made available to the VM/VMSS. + + :ivar gallery_applications: Specifies the gallery applications that should be made available to + the VM/VMSS. + :vartype gallery_applications: list[~azure.mgmt.computefleet.models.VMGalleryApplication] + """ + + _attribute_map = { + "gallery_applications": {"key": "galleryApplications", "type": "[VMGalleryApplication]"}, + } + + def __init__( + self, *, gallery_applications: Optional[List["_models.VMGalleryApplication"]] = None, **kwargs: Any + ) -> None: + """ + :keyword gallery_applications: Specifies the gallery applications that should be made available + to the VM/VMSS. + :paramtype gallery_applications: list[~azure.mgmt.computefleet.models.VMGalleryApplication] + """ + super().__init__(**kwargs) + self.gallery_applications = gallery_applications + + +class BasePriorityProfile(_serialization.Model): + """Contains common properties that are applicable to both Spot and Regular. + + :ivar capacity: Total capacity to achieve. It is currently in terms of number of VMs. + :vartype capacity: int + :ivar min_capacity: Minimum capacity to achieve which cannot be updated. If we will not be able + to "guarantee" minimum capacity, we will reject the request in the sync path itself. + :vartype min_capacity: int + """ + + _validation = { + "capacity": {"minimum": 0}, + "min_capacity": {"minimum": 0}, + } + + _attribute_map = { + "capacity": {"key": "capacity", "type": "int"}, + "min_capacity": {"key": "minCapacity", "type": "int"}, + } + + def __init__(self, *, capacity: Optional[int] = None, min_capacity: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword capacity: Total capacity to achieve. It is currently in terms of number of VMs. + :paramtype capacity: int + :keyword min_capacity: Minimum capacity to achieve which cannot be updated. If we will not be + able to "guarantee" minimum capacity, we will reject the request in the sync path itself. + :paramtype min_capacity: int + """ + super().__init__(**kwargs) + self.capacity = capacity + self.min_capacity = min_capacity + + +class BillingProfile(_serialization.Model): + """Specifies the billing related details of a Azure Spot VM or VMSS. Minimum api-version: + 2019-03-01. + + :ivar max_price: Specifies the maximum price you are willing to pay for a Azure Spot VM/VMSS. + This price is in US Dollars. :code:`
`:code:`
` This price will be compared with the + current Azure Spot price for the VM size. Also, the prices are compared at the time of + create/update of Azure Spot VM/VMSS and the operation will only succeed if the maxPrice is + greater than the current Azure Spot price. :code:`
`:code:`
` The maxPrice will also be + used for evicting a Azure Spot VM/VMSS if the current Azure Spot price goes beyond the maxPrice + after creation of VM/VMSS. :code:`
`:code:`
` Possible values are: + :code:`
`:code:`
` - Any decimal value greater than zero. Example: 0.01538 + :code:`
`:code:`
` -1 – indicates default price to be up-to on-demand. + :code:`
`:code:`
` You can set the maxPrice to -1 to indicate that the Azure Spot VM/VMSS + should not be evicted for price reasons. Also, the default max price is -1 if it is not + provided by you. :code:`
`:code:`
`Minimum api-version: 2019-03-01. + :vartype max_price: float + """ + + _attribute_map = { + "max_price": {"key": "maxPrice", "type": "float"}, + } + + def __init__(self, *, max_price: Optional[float] = None, **kwargs: Any) -> None: + """ + :keyword max_price: Specifies the maximum price you are willing to pay for a Azure Spot + VM/VMSS. This price is in US Dollars. :code:`
`:code:`
` This price will be compared with + the current Azure Spot price for the VM size. Also, the prices are compared at the time of + create/update of Azure Spot VM/VMSS and the operation will only succeed if the maxPrice is + greater than the current Azure Spot price. :code:`
`:code:`
` The maxPrice will also be + used for evicting a Azure Spot VM/VMSS if the current Azure Spot price goes beyond the maxPrice + after creation of VM/VMSS. :code:`
`:code:`
` Possible values are: + :code:`
`:code:`
` - Any decimal value greater than zero. Example: 0.01538 + :code:`
`:code:`
` -1 – indicates default price to be up-to on-demand. + :code:`
`:code:`
` You can set the maxPrice to -1 to indicate that the Azure Spot VM/VMSS + should not be evicted for price reasons. Also, the default max price is -1 if it is not + provided by you. :code:`
`:code:`
`Minimum api-version: 2019-03-01. + :paramtype max_price: float + """ + super().__init__(**kwargs) + self.max_price = max_price + + +class BootDiagnostics(_serialization.Model): + """Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot + to diagnose VM status. You can easily view the output of your console log. Azure also enables + you to see a screenshot of the VM from the hypervisor. + + :ivar enabled: Whether boot diagnostics should be enabled on the Virtual Machine. + :vartype enabled: bool + :ivar storage_uri: Uri of the storage account to use for placing the console output and + screenshot. If storageUri is not specified while enabling boot diagnostics, managed storage + will be used. + :vartype storage_uri: str + """ + + _attribute_map = { + "enabled": {"key": "enabled", "type": "bool"}, + "storage_uri": {"key": "storageUri", "type": "str"}, + } + + def __init__(self, *, enabled: Optional[bool] = None, storage_uri: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword enabled: Whether boot diagnostics should be enabled on the Virtual Machine. + :paramtype enabled: bool + :keyword storage_uri: Uri of the storage account to use for placing the console output and + screenshot. If storageUri is not specified while enabling boot diagnostics, managed storage + will be used. + :paramtype storage_uri: str + """ + super().__init__(**kwargs) + self.enabled = enabled + self.storage_uri = storage_uri + + +class CapacityReservationProfile(_serialization.Model): + """The parameters of a capacity reservation Profile. + + :ivar capacity_reservation_group: Specifies the capacity reservation group resource id that + should be used for allocating the virtual machine or scaleset vm instances provided enough + capacity has been reserved. Please refer to https://aka.ms/CapacityReservation for more + details. + :vartype capacity_reservation_group: ~azure.mgmt.computefleet.models.SubResource + """ + + _attribute_map = { + "capacity_reservation_group": {"key": "capacityReservationGroup", "type": "SubResource"}, + } + + def __init__(self, *, capacity_reservation_group: Optional["_models.SubResource"] = None, **kwargs: Any) -> None: + """ + :keyword capacity_reservation_group: Specifies the capacity reservation group resource id that + should be used for allocating the virtual machine or scaleset vm instances provided enough + capacity has been reserved. Please refer to https://aka.ms/CapacityReservation for more + details. + :paramtype capacity_reservation_group: ~azure.mgmt.computefleet.models.SubResource + """ + super().__init__(**kwargs) + self.capacity_reservation_group = capacity_reservation_group + + +class ComputeProfile(_serialization.Model): + """Compute Profile to use for running user's workloads. + + All required parameters must be populated in order to send to server. + + :ivar base_virtual_machine_profile: Base Virtual Machine Profile Properties to be specified + according to + "specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/{computeApiVersion}/virtualMachineScaleSet.json#/definitions/VirtualMachineScaleSetVMProfile". # pylint: disable=line-too-long + Required. + :vartype base_virtual_machine_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetVMProfile + :ivar compute_api_version: Specifies the Microsoft.Compute API version to use when creating + underlying Virtual Machine scale sets and Virtual Machines. + The default value will be the latest supported computeApiVersion by Compute Fleet. + :vartype compute_api_version: str + :ivar platform_fault_domain_count: Specifies the number of fault domains to use when creating + the underlying VMSS. + A fault domain is a logical group of hardware within an Azure datacenter. + VMs in the same fault domain share a common power source and network switch. + If not specified, defaults to 1, which represents "Max Spreading" (using as many fault domains + as possible). + This property cannot be updated. + :vartype platform_fault_domain_count: int + """ + + _validation = { + "base_virtual_machine_profile": {"required": True}, + } + + _attribute_map = { + "base_virtual_machine_profile": {"key": "baseVirtualMachineProfile", "type": "VirtualMachineScaleSetVMProfile"}, + "compute_api_version": {"key": "computeApiVersion", "type": "str"}, + "platform_fault_domain_count": {"key": "platformFaultDomainCount", "type": "int"}, + } + + def __init__( + self, + *, + base_virtual_machine_profile: "_models.VirtualMachineScaleSetVMProfile", + compute_api_version: Optional[str] = None, + platform_fault_domain_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword base_virtual_machine_profile: Base Virtual Machine Profile Properties to be specified + according to + "specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/{computeApiVersion}/virtualMachineScaleSet.json#/definitions/VirtualMachineScaleSetVMProfile". # pylint: disable=line-too-long + Required. + :paramtype base_virtual_machine_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetVMProfile + :keyword compute_api_version: Specifies the Microsoft.Compute API version to use when creating + underlying Virtual Machine scale sets and Virtual Machines. + The default value will be the latest supported computeApiVersion by Compute Fleet. + :paramtype compute_api_version: str + :keyword platform_fault_domain_count: Specifies the number of fault domains to use when + creating the underlying VMSS. + A fault domain is a logical group of hardware within an Azure datacenter. + VMs in the same fault domain share a common power source and network switch. + If not specified, defaults to 1, which represents "Max Spreading" (using as many fault domains + as possible). + This property cannot be updated. + :paramtype platform_fault_domain_count: int + """ + super().__init__(**kwargs) + self.base_virtual_machine_profile = base_virtual_machine_profile + self.compute_api_version = compute_api_version + self.platform_fault_domain_count = platform_fault_domain_count + + +class ComputeProfileUpdate(_serialization.Model): + """Compute Profile to use for running user's workloads. + + :ivar base_virtual_machine_profile: Base Virtual Machine Profile Properties to be specified + according to + "specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/{computeApiVersion}/virtualMachineScaleSet.json#/definitions/VirtualMachineScaleSetVMProfile". # pylint: disable=line-too-long + :vartype base_virtual_machine_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetVMProfile + :ivar compute_api_version: Specifies the Microsoft.Compute API version to use when creating + underlying Virtual Machine scale sets and Virtual Machines. + The default value will be the latest supported computeApiVersion by Compute Fleet. + :vartype compute_api_version: str + :ivar platform_fault_domain_count: Specifies the number of fault domains to use when creating + the underlying VMSS. + A fault domain is a logical group of hardware within an Azure datacenter. + VMs in the same fault domain share a common power source and network switch. + If not specified, defaults to 1, which represents "Max Spreading" (using as many fault domains + as possible). + This property cannot be updated. + :vartype platform_fault_domain_count: int + """ + + _attribute_map = { + "base_virtual_machine_profile": {"key": "baseVirtualMachineProfile", "type": "VirtualMachineScaleSetVMProfile"}, + "compute_api_version": {"key": "computeApiVersion", "type": "str"}, + "platform_fault_domain_count": {"key": "platformFaultDomainCount", "type": "int"}, + } + + def __init__( + self, + *, + base_virtual_machine_profile: Optional["_models.VirtualMachineScaleSetVMProfile"] = None, + compute_api_version: Optional[str] = None, + platform_fault_domain_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword base_virtual_machine_profile: Base Virtual Machine Profile Properties to be specified + according to + "specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/{computeApiVersion}/virtualMachineScaleSet.json#/definitions/VirtualMachineScaleSetVMProfile". # pylint: disable=line-too-long + :paramtype base_virtual_machine_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetVMProfile + :keyword compute_api_version: Specifies the Microsoft.Compute API version to use when creating + underlying Virtual Machine scale sets and Virtual Machines. + The default value will be the latest supported computeApiVersion by Compute Fleet. + :paramtype compute_api_version: str + :keyword platform_fault_domain_count: Specifies the number of fault domains to use when + creating the underlying VMSS. + A fault domain is a logical group of hardware within an Azure datacenter. + VMs in the same fault domain share a common power source and network switch. + If not specified, defaults to 1, which represents "Max Spreading" (using as many fault domains + as possible). + This property cannot be updated. + :paramtype platform_fault_domain_count: int + """ + super().__init__(**kwargs) + self.base_virtual_machine_profile = base_virtual_machine_profile + self.compute_api_version = compute_api_version + self.platform_fault_domain_count = platform_fault_domain_count + + +class DiagnosticsProfile(_serialization.Model): + """Specifies the boot diagnostic settings state. Minimum api-version: 2015-06-15. + + :ivar boot_diagnostics: Boot Diagnostics is a debugging feature which allows you to view + Console Output and Screenshot to diagnose VM status. **NOTE**\\ : If storageUri is being + specified then ensure that the storage account is in the same region and subscription as the + VM. You can easily view the output of your console log. Azure also enables you to see a + screenshot of the VM from the hypervisor. + :vartype boot_diagnostics: ~azure.mgmt.computefleet.models.BootDiagnostics + """ + + _attribute_map = { + "boot_diagnostics": {"key": "bootDiagnostics", "type": "BootDiagnostics"}, + } + + def __init__(self, *, boot_diagnostics: Optional["_models.BootDiagnostics"] = None, **kwargs: Any) -> None: + """ + :keyword boot_diagnostics: Boot Diagnostics is a debugging feature which allows you to view + Console Output and Screenshot to diagnose VM status. **NOTE**\\ : If storageUri is being + specified then ensure that the storage account is in the same region and subscription as the + VM. You can easily view the output of your console log. Azure also enables you to see a + screenshot of the VM from the hypervisor. + :paramtype boot_diagnostics: ~azure.mgmt.computefleet.models.BootDiagnostics + """ + super().__init__(**kwargs) + self.boot_diagnostics = boot_diagnostics + + +class DiffDiskSettings(_serialization.Model): + """Describes the parameters of ephemeral disk settings that can be specified for operating system + disk. **Note:** The ephemeral disk settings can only be specified for managed disk. + + :ivar option: Specifies the ephemeral disk settings for operating system disk. "Local" + :vartype option: str or ~azure.mgmt.computefleet.models.DiffDiskOptions + :ivar placement: Specifies the ephemeral disk placement for operating system disk. Possible + values are: **CacheDisk,** **ResourceDisk.** The defaulting behavior is: **CacheDisk** if one + is configured for the VM size otherwise **ResourceDisk** is used. Refer to the VM size + documentation for Windows VM at https://docs.microsoft.com/azure/virtual-machines/windows/sizes + and Linux VM at https://docs.microsoft.com/azure/virtual-machines/linux/sizes to check which VM + sizes exposes a cache disk. Known values are: "CacheDisk" and "ResourceDisk". + :vartype placement: str or ~azure.mgmt.computefleet.models.DiffDiskPlacement + """ + + _attribute_map = { + "option": {"key": "option", "type": "str"}, + "placement": {"key": "placement", "type": "str"}, + } + + def __init__( + self, + *, + option: Optional[Union[str, "_models.DiffDiskOptions"]] = None, + placement: Optional[Union[str, "_models.DiffDiskPlacement"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword option: Specifies the ephemeral disk settings for operating system disk. "Local" + :paramtype option: str or ~azure.mgmt.computefleet.models.DiffDiskOptions + :keyword placement: Specifies the ephemeral disk placement for operating system disk. Possible + values are: **CacheDisk,** **ResourceDisk.** The defaulting behavior is: **CacheDisk** if one + is configured for the VM size otherwise **ResourceDisk** is used. Refer to the VM size + documentation for Windows VM at https://docs.microsoft.com/azure/virtual-machines/windows/sizes + and Linux VM at https://docs.microsoft.com/azure/virtual-machines/linux/sizes to check which VM + sizes exposes a cache disk. Known values are: "CacheDisk" and "ResourceDisk". + :paramtype placement: str or ~azure.mgmt.computefleet.models.DiffDiskPlacement + """ + super().__init__(**kwargs) + self.option = option + self.placement = placement + + +class SubResource(_serialization.Model): + """SubResource. + + :ivar id: Resource Id. + :vartype id: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: Resource Id. + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class DiskEncryptionSetParameters(SubResource): + """Describes the parameter of customer managed disk encryption set resource id that can be + specified for disk. **Note:** The disk encryption set resource id can only be specified for + managed disk. Please refer https://aka.ms/mdssewithcmkoverview for more details. + + :ivar id: Resource Id. + :vartype id: str + """ + + +class EncryptionIdentity(_serialization.Model): + """Specifies the Managed Identity used by ADE to get access token for keyvault operations. + + :ivar user_assigned_identity_resource_id: Specifies ARM Resource ID of one of the user + identities associated with the VM. + :vartype user_assigned_identity_resource_id: str + """ + + _attribute_map = { + "user_assigned_identity_resource_id": {"key": "userAssignedIdentityResourceId", "type": "str"}, + } + + def __init__(self, *, user_assigned_identity_resource_id: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword user_assigned_identity_resource_id: Specifies ARM Resource ID of one of the user + identities associated with the VM. + :paramtype user_assigned_identity_resource_id: str + """ + super().__init__(**kwargs) + self.user_assigned_identity_resource_id = user_assigned_identity_resource_id + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.computefleet.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.computefleet.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.computefleet.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.computefleet.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.computefleet.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which + has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.computefleet.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + } + + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + """ + super().__init__(**kwargs) + self.tags = tags + self.location = location + + +class Fleet(TrackedResource): # pylint: disable=too-many-instance-attributes + """An Compute Fleet resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.computefleet.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar zones: Zones in which the Compute Fleet is available. + :vartype zones: list[str] + :ivar identity: The managed service identities assigned to this resource. + :vartype identity: ~azure.mgmt.computefleet.models.ManagedServiceIdentity + :ivar plan: Details of the resource plan. + :vartype plan: ~azure.mgmt.computefleet.models.Plan + :ivar provisioning_state: The status of the last operation. Known values are: "Succeeded", + "Failed", "Canceled", "Creating", "Updating", "Deleting", and "Migrating". + :vartype provisioning_state: str or ~azure.mgmt.computefleet.models.ProvisioningState + :ivar spot_priority_profile: Configuration Options for Spot instances in Compute Fleet. + :vartype spot_priority_profile: ~azure.mgmt.computefleet.models.SpotPriorityProfile + :ivar regular_priority_profile: Configuration Options for Regular instances in Compute Fleet. + :vartype regular_priority_profile: ~azure.mgmt.computefleet.models.RegularPriorityProfile + :ivar vm_sizes_profile: List of VM sizes supported for Compute Fleet. + :vartype vm_sizes_profile: list[~azure.mgmt.computefleet.models.VmSizeProfile] + :ivar compute_profile: Compute Profile to use for running user's workloads. + :vartype compute_profile: ~azure.mgmt.computefleet.models.ComputeProfile + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "location": {"required": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "zones": {"key": "zones", "type": "[str]"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, + "plan": {"key": "plan", "type": "Plan"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "spot_priority_profile": {"key": "properties.spotPriorityProfile", "type": "SpotPriorityProfile"}, + "regular_priority_profile": {"key": "properties.regularPriorityProfile", "type": "RegularPriorityProfile"}, + "vm_sizes_profile": {"key": "properties.vmSizesProfile", "type": "[VmSizeProfile]"}, + "compute_profile": {"key": "properties.computeProfile", "type": "ComputeProfile"}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + zones: Optional[List[str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = None, + plan: Optional["_models.Plan"] = None, + spot_priority_profile: Optional["_models.SpotPriorityProfile"] = None, + regular_priority_profile: Optional["_models.RegularPriorityProfile"] = None, + vm_sizes_profile: Optional[List["_models.VmSizeProfile"]] = None, + compute_profile: Optional["_models.ComputeProfile"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + :keyword zones: Zones in which the Compute Fleet is available. + :paramtype zones: list[str] + :keyword identity: The managed service identities assigned to this resource. + :paramtype identity: ~azure.mgmt.computefleet.models.ManagedServiceIdentity + :keyword plan: Details of the resource plan. + :paramtype plan: ~azure.mgmt.computefleet.models.Plan + :keyword spot_priority_profile: Configuration Options for Spot instances in Compute Fleet. + :paramtype spot_priority_profile: ~azure.mgmt.computefleet.models.SpotPriorityProfile + :keyword regular_priority_profile: Configuration Options for Regular instances in Compute + Fleet. + :paramtype regular_priority_profile: ~azure.mgmt.computefleet.models.RegularPriorityProfile + :keyword vm_sizes_profile: List of VM sizes supported for Compute Fleet. + :paramtype vm_sizes_profile: list[~azure.mgmt.computefleet.models.VmSizeProfile] + :keyword compute_profile: Compute Profile to use for running user's workloads. + :paramtype compute_profile: ~azure.mgmt.computefleet.models.ComputeProfile + """ + super().__init__(tags=tags, location=location, **kwargs) + self.zones = zones + self.identity = identity + self.plan = plan + self.provisioning_state = None + self.spot_priority_profile = spot_priority_profile + self.regular_priority_profile = regular_priority_profile + self.vm_sizes_profile = vm_sizes_profile + self.compute_profile = compute_profile + + +class FleetListResult(_serialization.Model): + """The response of a Fleet list operation. + + All required parameters must be populated in order to send to server. + + :ivar value: The Fleet items on this page. Required. + :vartype value: list[~azure.mgmt.computefleet.models.Fleet] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Fleet]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: List["_models.Fleet"], next_link: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword value: The Fleet items on this page. Required. + :paramtype value: list[~azure.mgmt.computefleet.models.Fleet] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class FleetPropertiesUpdate(_serialization.Model): + """Details of the Compute Fleet. + + :ivar spot_priority_profile: Configuration Options for Spot instances in Compute Fleet. + :vartype spot_priority_profile: ~azure.mgmt.computefleet.models.SpotPriorityProfile + :ivar regular_priority_profile: Configuration Options for Regular instances in Compute Fleet. + :vartype regular_priority_profile: ~azure.mgmt.computefleet.models.RegularPriorityProfile + :ivar vm_sizes_profile: List of VM sizes supported for Compute Fleet. + :vartype vm_sizes_profile: list[~azure.mgmt.computefleet.models.VmSizeProfile] + :ivar compute_profile: Compute Profile to use for running user's workloads. + :vartype compute_profile: ~azure.mgmt.computefleet.models.ComputeProfileUpdate + """ + + _attribute_map = { + "spot_priority_profile": {"key": "spotPriorityProfile", "type": "SpotPriorityProfile"}, + "regular_priority_profile": {"key": "regularPriorityProfile", "type": "RegularPriorityProfile"}, + "vm_sizes_profile": {"key": "vmSizesProfile", "type": "[VmSizeProfile]"}, + "compute_profile": {"key": "computeProfile", "type": "ComputeProfileUpdate"}, + } + + def __init__( + self, + *, + spot_priority_profile: Optional["_models.SpotPriorityProfile"] = None, + regular_priority_profile: Optional["_models.RegularPriorityProfile"] = None, + vm_sizes_profile: Optional[List["_models.VmSizeProfile"]] = None, + compute_profile: Optional["_models.ComputeProfileUpdate"] = None, + **kwargs: Any + ) -> None: + """ + :keyword spot_priority_profile: Configuration Options for Spot instances in Compute Fleet. + :paramtype spot_priority_profile: ~azure.mgmt.computefleet.models.SpotPriorityProfile + :keyword regular_priority_profile: Configuration Options for Regular instances in Compute + Fleet. + :paramtype regular_priority_profile: ~azure.mgmt.computefleet.models.RegularPriorityProfile + :keyword vm_sizes_profile: List of VM sizes supported for Compute Fleet. + :paramtype vm_sizes_profile: list[~azure.mgmt.computefleet.models.VmSizeProfile] + :keyword compute_profile: Compute Profile to use for running user's workloads. + :paramtype compute_profile: ~azure.mgmt.computefleet.models.ComputeProfileUpdate + """ + super().__init__(**kwargs) + self.spot_priority_profile = spot_priority_profile + self.regular_priority_profile = regular_priority_profile + self.vm_sizes_profile = vm_sizes_profile + self.compute_profile = compute_profile + + +class FleetUpdate(_serialization.Model): + """Fleet Update Model. + + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar identity: Updatable managed service identity. + :vartype identity: ~azure.mgmt.computefleet.models.ManagedServiceIdentityUpdate + :ivar plan: Updatable resource plan. + :vartype plan: ~azure.mgmt.computefleet.models.ResourcePlanUpdate + :ivar properties: RP-specific updatable properties. + :vartype properties: ~azure.mgmt.computefleet.models.FleetPropertiesUpdate + """ + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + "identity": {"key": "identity", "type": "ManagedServiceIdentityUpdate"}, + "plan": {"key": "plan", "type": "ResourcePlanUpdate"}, + "properties": {"key": "properties", "type": "FleetPropertiesUpdate"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentityUpdate"] = None, + plan: Optional["_models.ResourcePlanUpdate"] = None, + properties: Optional["_models.FleetPropertiesUpdate"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword identity: Updatable managed service identity. + :paramtype identity: ~azure.mgmt.computefleet.models.ManagedServiceIdentityUpdate + :keyword plan: Updatable resource plan. + :paramtype plan: ~azure.mgmt.computefleet.models.ResourcePlanUpdate + :keyword properties: RP-specific updatable properties. + :paramtype properties: ~azure.mgmt.computefleet.models.FleetPropertiesUpdate + """ + super().__init__(**kwargs) + self.tags = tags + self.identity = identity + self.plan = plan + self.properties = properties + + +class ImageReference(SubResource): + """Specifies information about the image to use. You can specify information about platform + images, marketplace images, or virtual machine images. This element is required when you want + to use a platform image, marketplace image, or virtual machine image, but is not used in other + creation operations. NOTE: Image reference publisher and offer can only be set when you create + the scale set. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar publisher: The image publisher. + :vartype publisher: str + :ivar offer: Specifies the offer of the platform image or marketplace image used to create the + virtual machine. + :vartype offer: str + :ivar sku: The image SKU. + :vartype sku: str + :ivar version: Specifies the version of the platform image or marketplace image used to create + the virtual machine. The allowed formats are Major.Minor.Build or 'latest'. Major, Minor, and + Build are decimal numbers. Specify 'latest' to use the latest version of an image available at + deploy time. Even if you use 'latest', the VM image will not automatically update after deploy + time even if a new version becomes available. Please do not use field 'version' for gallery + image deployment, gallery image should always use 'id' field for deployment, to use 'latest' + version of gallery image, just set + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageName}' # pylint: disable=line-too-long + in the 'id' field without version input. + :vartype version: str + :ivar exact_version: Specifies in decimal numbers, the version of platform image or marketplace + image used to create the virtual machine. This readonly field differs from 'version', only if + the value specified in 'version' field is 'latest'. + :vartype exact_version: str + :ivar shared_gallery_image_id: Specified the shared gallery image unique id for vm deployment. + This can be fetched from shared gallery image GET call. + :vartype shared_gallery_image_id: str + :ivar community_gallery_image_id: Specified the community gallery image unique id for vm + deployment. This can be fetched from community gallery image GET call. + :vartype community_gallery_image_id: str + """ + + _validation = { + "exact_version": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "offer": {"key": "offer", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "version": {"key": "version", "type": "str"}, + "exact_version": {"key": "exactVersion", "type": "str"}, + "shared_gallery_image_id": {"key": "sharedGalleryImageId", "type": "str"}, + "community_gallery_image_id": {"key": "communityGalleryImageId", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + publisher: Optional[str] = None, + offer: Optional[str] = None, + sku: Optional[str] = None, + version: Optional[str] = None, + shared_gallery_image_id: Optional[str] = None, + community_gallery_image_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Resource Id. + :paramtype id: str + :keyword publisher: The image publisher. + :paramtype publisher: str + :keyword offer: Specifies the offer of the platform image or marketplace image used to create + the virtual machine. + :paramtype offer: str + :keyword sku: The image SKU. + :paramtype sku: str + :keyword version: Specifies the version of the platform image or marketplace image used to + create the virtual machine. The allowed formats are Major.Minor.Build or 'latest'. Major, + Minor, and Build are decimal numbers. Specify 'latest' to use the latest version of an image + available at deploy time. Even if you use 'latest', the VM image will not automatically update + after deploy time even if a new version becomes available. Please do not use field 'version' + for gallery image deployment, gallery image should always use 'id' field for deployment, to use + 'latest' version of gallery image, just set + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageName}' # pylint: disable=line-too-long + in the 'id' field without version input. + :paramtype version: str + :keyword shared_gallery_image_id: Specified the shared gallery image unique id for vm + deployment. This can be fetched from shared gallery image GET call. + :paramtype shared_gallery_image_id: str + :keyword community_gallery_image_id: Specified the community gallery image unique id for vm + deployment. This can be fetched from community gallery image GET call. + :paramtype community_gallery_image_id: str + """ + super().__init__(id=id, **kwargs) + self.publisher = publisher + self.offer = offer + self.sku = sku + self.version = version + self.exact_version = None + self.shared_gallery_image_id = shared_gallery_image_id + self.community_gallery_image_id = community_gallery_image_id + + +class InnerError(_serialization.Model): + """Inner error details. + + :ivar exceptiontype: The exception type. + :vartype exceptiontype: str + :ivar errordetail: The internal error message or exception dump. + :vartype errordetail: str + """ + + _attribute_map = { + "exceptiontype": {"key": "exceptiontype", "type": "str"}, + "errordetail": {"key": "errordetail", "type": "str"}, + } + + def __init__( + self, *, exceptiontype: Optional[str] = None, errordetail: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword exceptiontype: The exception type. + :paramtype exceptiontype: str + :keyword errordetail: The internal error message or exception dump. + :paramtype errordetail: str + """ + super().__init__(**kwargs) + self.exceptiontype = exceptiontype + self.errordetail = errordetail + + +class InstanceViewStatus(_serialization.Model): + """Instance view status. + + :ivar code: The status code. + :vartype code: str + :ivar level: The level code. Known values are: "Info", "Warning", and "Error". + :vartype level: str or ~azure.mgmt.computefleet.models.StatusLevelTypes + :ivar display_status: The short localizable label for the status. + :vartype display_status: str + :ivar message: The detailed status message, including for alerts and error messages. + :vartype message: str + :ivar time: The time of the status. + :vartype time: ~datetime.datetime + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "level": {"key": "level", "type": "str"}, + "display_status": {"key": "displayStatus", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "time": {"key": "time", "type": "iso-8601"}, + } + + def __init__( + self, + *, + code: Optional[str] = None, + level: Optional[Union[str, "_models.StatusLevelTypes"]] = None, + display_status: Optional[str] = None, + message: Optional[str] = None, + time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword code: The status code. + :paramtype code: str + :keyword level: The level code. Known values are: "Info", "Warning", and "Error". + :paramtype level: str or ~azure.mgmt.computefleet.models.StatusLevelTypes + :keyword display_status: The short localizable label for the status. + :paramtype display_status: str + :keyword message: The detailed status message, including for alerts and error messages. + :paramtype message: str + :keyword time: The time of the status. + :paramtype time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.code = code + self.level = level + self.display_status = display_status + self.message = message + self.time = time + + +class KeyVaultSecretReference(_serialization.Model): + """Describes a reference to Key Vault Secret. + + All required parameters must be populated in order to send to server. + + :ivar secret_url: The URL referencing a secret in a Key Vault. Required. + :vartype secret_url: str + :ivar source_vault: The relative URL of the Key Vault containing the secret. Required. + :vartype source_vault: ~azure.mgmt.computefleet.models.SubResource + """ + + _validation = { + "secret_url": {"required": True}, + "source_vault": {"required": True}, + } + + _attribute_map = { + "secret_url": {"key": "secretUrl", "type": "str"}, + "source_vault": {"key": "sourceVault", "type": "SubResource"}, + } + + def __init__(self, *, secret_url: str, source_vault: "_models.SubResource", **kwargs: Any) -> None: + """ + :keyword secret_url: The URL referencing a secret in a Key Vault. Required. + :paramtype secret_url: str + :keyword source_vault: The relative URL of the Key Vault containing the secret. Required. + :paramtype source_vault: ~azure.mgmt.computefleet.models.SubResource + """ + super().__init__(**kwargs) + self.secret_url = secret_url + self.source_vault = source_vault + + +class LinuxConfiguration(_serialization.Model): + """Specifies the Linux operating system settings on the virtual machine. For a list of supported + Linux distributions, see `Linux on Azure-Endorsed Distributions + `_. + + :ivar disable_password_authentication: Specifies whether password authentication should be + disabled. + :vartype disable_password_authentication: bool + :ivar ssh: Specifies the ssh key configuration for a Linux OS. + :vartype ssh: ~azure.mgmt.computefleet.models.SshConfiguration + :ivar provision_vm_agent: Indicates whether virtual machine agent should be provisioned on the + virtual machine. When this property is not specified in the request body, default behavior is + to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can + be added to the VM later. + :vartype provision_vm_agent: bool + :ivar patch_settings: [Preview Feature] Specifies settings related to VM Guest Patching on + Linux. + :vartype patch_settings: ~azure.mgmt.computefleet.models.LinuxPatchSettings + :ivar enable_vm_agent_platform_updates: Indicates whether VMAgent Platform Updates is enabled + for the Linux virtual machine. Default value is false. + :vartype enable_vm_agent_platform_updates: bool + """ + + _attribute_map = { + "disable_password_authentication": {"key": "disablePasswordAuthentication", "type": "bool"}, + "ssh": {"key": "ssh", "type": "SshConfiguration"}, + "provision_vm_agent": {"key": "provisionVMAgent", "type": "bool"}, + "patch_settings": {"key": "patchSettings", "type": "LinuxPatchSettings"}, + "enable_vm_agent_platform_updates": {"key": "enableVMAgentPlatformUpdates", "type": "bool"}, + } + + def __init__( + self, + *, + disable_password_authentication: Optional[bool] = None, + ssh: Optional["_models.SshConfiguration"] = None, + provision_vm_agent: Optional[bool] = None, + patch_settings: Optional["_models.LinuxPatchSettings"] = None, + enable_vm_agent_platform_updates: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword disable_password_authentication: Specifies whether password authentication should be + disabled. + :paramtype disable_password_authentication: bool + :keyword ssh: Specifies the ssh key configuration for a Linux OS. + :paramtype ssh: ~azure.mgmt.computefleet.models.SshConfiguration + :keyword provision_vm_agent: Indicates whether virtual machine agent should be provisioned on + the virtual machine. When this property is not specified in the request body, default behavior + is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions + can be added to the VM later. + :paramtype provision_vm_agent: bool + :keyword patch_settings: [Preview Feature] Specifies settings related to VM Guest Patching on + Linux. + :paramtype patch_settings: ~azure.mgmt.computefleet.models.LinuxPatchSettings + :keyword enable_vm_agent_platform_updates: Indicates whether VMAgent Platform Updates is + enabled for the Linux virtual machine. Default value is false. + :paramtype enable_vm_agent_platform_updates: bool + """ + super().__init__(**kwargs) + self.disable_password_authentication = disable_password_authentication + self.ssh = ssh + self.provision_vm_agent = provision_vm_agent + self.patch_settings = patch_settings + self.enable_vm_agent_platform_updates = enable_vm_agent_platform_updates + + +class LinuxPatchSettings(_serialization.Model): + """Specifies settings related to VM Guest Patching on Linux. + + :ivar patch_mode: Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual + machines associated to virtual machine scale set with OrchestrationMode as Flexible.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` **ImageDefault** - The + virtual machine's default patching configuration is used. :code:`
`:code:`
` + **AutomaticByPlatform** - The virtual machine will be automatically updated by the platform. + The property provisionVMAgent must be true. Known values are: "ImageDefault" and + "AutomaticByPlatform". + :vartype patch_mode: str or ~azure.mgmt.computefleet.models.LinuxVMGuestPatchMode + :ivar assessment_mode: Specifies the mode of VM Guest Patch Assessment for the IaaS virtual + machine.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` + **ImageDefault** - You control the timing of patch assessments on a virtual machine. :code:`
`:code:`
` **AutomaticByPlatform** - The platform will trigger periodic patch + assessments. The property provisionVMAgent must be true. Known values are: "ImageDefault" and + "AutomaticByPlatform". + :vartype assessment_mode: str or ~azure.mgmt.computefleet.models.LinuxPatchAssessmentMode + :ivar automatic_by_platform_settings: Specifies additional settings for patch mode + AutomaticByPlatform in VM Guest Patching on Linux. + :vartype automatic_by_platform_settings: + ~azure.mgmt.computefleet.models.LinuxVMGuestPatchAutomaticByPlatformSettings + """ + + _attribute_map = { + "patch_mode": {"key": "patchMode", "type": "str"}, + "assessment_mode": {"key": "assessmentMode", "type": "str"}, + "automatic_by_platform_settings": { + "key": "automaticByPlatformSettings", + "type": "LinuxVMGuestPatchAutomaticByPlatformSettings", + }, + } + + def __init__( + self, + *, + patch_mode: Optional[Union[str, "_models.LinuxVMGuestPatchMode"]] = None, + assessment_mode: Optional[Union[str, "_models.LinuxPatchAssessmentMode"]] = None, + automatic_by_platform_settings: Optional["_models.LinuxVMGuestPatchAutomaticByPlatformSettings"] = None, + **kwargs: Any + ) -> None: + """ + :keyword patch_mode: Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual + machines associated to virtual machine scale set with OrchestrationMode as Flexible.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` **ImageDefault** - The + virtual machine's default patching configuration is used. :code:`
`:code:`
` + **AutomaticByPlatform** - The virtual machine will be automatically updated by the platform. + The property provisionVMAgent must be true. Known values are: "ImageDefault" and + "AutomaticByPlatform". + :paramtype patch_mode: str or ~azure.mgmt.computefleet.models.LinuxVMGuestPatchMode + :keyword assessment_mode: Specifies the mode of VM Guest Patch Assessment for the IaaS virtual + machine.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` + **ImageDefault** - You control the timing of patch assessments on a virtual machine. :code:`
`:code:`
` **AutomaticByPlatform** - The platform will trigger periodic patch + assessments. The property provisionVMAgent must be true. Known values are: "ImageDefault" and + "AutomaticByPlatform". + :paramtype assessment_mode: str or ~azure.mgmt.computefleet.models.LinuxPatchAssessmentMode + :keyword automatic_by_platform_settings: Specifies additional settings for patch mode + AutomaticByPlatform in VM Guest Patching on Linux. + :paramtype automatic_by_platform_settings: + ~azure.mgmt.computefleet.models.LinuxVMGuestPatchAutomaticByPlatformSettings + """ + super().__init__(**kwargs) + self.patch_mode = patch_mode + self.assessment_mode = assessment_mode + self.automatic_by_platform_settings = automatic_by_platform_settings + + +class LinuxVMGuestPatchAutomaticByPlatformSettings(_serialization.Model): # pylint: disable=name-too-long + """Specifies additional settings to be applied when patch mode AutomaticByPlatform is selected in + Linux patch settings. + + :ivar reboot_setting: Specifies the reboot setting for all AutomaticByPlatform patch + installation operations. Known values are: "Unknown", "IfRequired", "Never", and "Always". + :vartype reboot_setting: str or + ~azure.mgmt.computefleet.models.LinuxVMGuestPatchAutomaticByPlatformRebootSetting + :ivar bypass_platform_safety_checks_on_user_schedule: Enables customer to schedule patching + without accidental upgrades. + :vartype bypass_platform_safety_checks_on_user_schedule: bool + """ + + _attribute_map = { + "reboot_setting": {"key": "rebootSetting", "type": "str"}, + "bypass_platform_safety_checks_on_user_schedule": { + "key": "bypassPlatformSafetyChecksOnUserSchedule", + "type": "bool", + }, + } + + def __init__( + self, + *, + reboot_setting: Optional[Union[str, "_models.LinuxVMGuestPatchAutomaticByPlatformRebootSetting"]] = None, + bypass_platform_safety_checks_on_user_schedule: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword reboot_setting: Specifies the reboot setting for all AutomaticByPlatform patch + installation operations. Known values are: "Unknown", "IfRequired", "Never", and "Always". + :paramtype reboot_setting: str or + ~azure.mgmt.computefleet.models.LinuxVMGuestPatchAutomaticByPlatformRebootSetting + :keyword bypass_platform_safety_checks_on_user_schedule: Enables customer to schedule patching + without accidental upgrades. + :paramtype bypass_platform_safety_checks_on_user_schedule: bool + """ + super().__init__(**kwargs) + self.reboot_setting = reboot_setting + self.bypass_platform_safety_checks_on_user_schedule = bypass_platform_safety_checks_on_user_schedule + + +class ManagedServiceIdentity(_serialization.Model): + """Managed service identity (system assigned and/or user assigned identities). + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar principal_id: The service principal ID of the system assigned identity. This property + will only be provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of the system assigned identity. This property will only be + provided for a system assigned identity. + :vartype tenant_id: str + :ivar type: Type of managed service identity (where both SystemAssigned and UserAssigned types + are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", + "SystemAssigned,UserAssigned", and "SystemAssigned, UserAssigned". + :vartype type: str or ~azure.mgmt.computefleet.models.ManagedServiceIdentityType + :ivar user_assigned_identities: The set of user assigned identities associated with the + resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long + The dictionary values can be empty objects ({}) in requests. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.computefleet.models.UserAssignedIdentity] + """ + + _validation = { + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, + "type": {"required": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, + } + + def __init__( + self, + *, + type: Union[str, "_models.ManagedServiceIdentityType"], + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: Type of managed service identity (where both SystemAssigned and UserAssigned + types are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", + "SystemAssigned,UserAssigned", and "SystemAssigned, UserAssigned". + :paramtype type: str or ~azure.mgmt.computefleet.models.ManagedServiceIdentityType + :keyword user_assigned_identities: The set of user assigned identities associated with the + resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long + The dictionary values can be empty objects ({}) in requests. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.computefleet.models.UserAssignedIdentity] + """ + super().__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class ManagedServiceIdentityUpdate(_serialization.Model): + """The template for adding optional properties. + + :ivar type: The type of managed identity assigned to this resource. Known values are: "None", + "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned", and "SystemAssigned, + UserAssigned". + :vartype type: str or ~azure.mgmt.computefleet.models.ManagedServiceIdentityType + :ivar user_assigned_identities: The identities assigned to this resource by the user. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.computefleet.models.UserAssignedIdentity] + """ + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "_models.ManagedServiceIdentityType"]] = None, + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword type: The type of managed identity assigned to this resource. Known values are: + "None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned", and "SystemAssigned, + UserAssigned". + :paramtype type: str or ~azure.mgmt.computefleet.models.ManagedServiceIdentityType + :keyword user_assigned_identities: The identities assigned to this resource by the user. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.computefleet.models.UserAssignedIdentity] + """ + super().__init__(**kwargs) + self.type = type + self.user_assigned_identities = user_assigned_identities + + +class Operation(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.computefleet.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.computefleet.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.computefleet.models.ActionType + """ + + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: + """ + :keyword display: Localized display information for this particular operation. + :paramtype display: ~azure.mgmt.computefleet.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = None + self.is_data_action = None + self.display = display + self.origin = None + self.action_type = None + + +class OperationDisplay(_serialization.Model): + """Localized display information for this particular operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". + :vartype provider: str + :ivar resource: The localized friendly name of the resource type related to this operation. + E.g. "Virtual Machines" or "Job Schedule Collections". + :vartype resource: str + :ivar operation: The concise, localized friendly name for the operation; suitable for + dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". + :vartype operation: str + :ivar description: The short, localized friendly description of the operation; suitable for + tool tips and detailed views. + :vartype description: str + """ + + _validation = { + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(_serialization.Model): + """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link + to get the next set of results. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of operations supported by the resource provider. + :vartype value: list[~azure.mgmt.computefleet.models.Operation] + :ivar next_link: URL to get the next set of operation list results (if there are any). + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class OSImageNotificationProfile(_serialization.Model): + """OSImageNotificationProfile. + + :ivar not_before_timeout: Length of time a Virtual Machine being reimaged or having its OS + upgraded will have to potentially approve the OS Image Scheduled Event before the event is auto + approved (timed out). The configuration is specified in ISO 8601 format, and the value must be + 15 minutes (PT15M). + :vartype not_before_timeout: str + :ivar enable: Specifies whether the OS Image Scheduled event is enabled or disabled. + :vartype enable: bool + """ + + _attribute_map = { + "not_before_timeout": {"key": "notBeforeTimeout", "type": "str"}, + "enable": {"key": "enable", "type": "bool"}, + } + + def __init__( + self, *, not_before_timeout: Optional[str] = None, enable: Optional[bool] = None, **kwargs: Any + ) -> None: + """ + :keyword not_before_timeout: Length of time a Virtual Machine being reimaged or having its OS + upgraded will have to potentially approve the OS Image Scheduled Event before the event is auto + approved (timed out). The configuration is specified in ISO 8601 format, and the value must be + 15 minutes (PT15M). + :paramtype not_before_timeout: str + :keyword enable: Specifies whether the OS Image Scheduled event is enabled or disabled. + :paramtype enable: bool + """ + super().__init__(**kwargs) + self.not_before_timeout = not_before_timeout + self.enable = enable + + +class PatchSettings(_serialization.Model): + """Specifies settings related to VM Guest Patching on Windows. + + :ivar patch_mode: Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual + machines associated to virtual machine scale set with OrchestrationMode as Flexible.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` **Manual** - You control + the application of patches to a virtual machine. You do this by applying patches manually + inside the VM. In this mode, automatic updates are disabled; the property + WindowsConfiguration.enableAutomaticUpdates must be false:code:`
`:code:`
` + **AutomaticByOS** - The virtual machine will automatically be updated by the OS. The property + WindowsConfiguration.enableAutomaticUpdates must be true. :code:`
`:code:`
` + **AutomaticByPlatform** - the virtual machine will automatically updated by the platform. The + properties provisionVMAgent and WindowsConfiguration.enableAutomaticUpdates must be true. Known + values are: "Manual", "AutomaticByOS", and "AutomaticByPlatform". + :vartype patch_mode: str or ~azure.mgmt.computefleet.models.WindowsVMGuestPatchMode + :ivar enable_hotpatching: Enables customers to patch their Azure VMs without requiring a + reboot. For enableHotpatching, the 'provisionVMAgent' must be set to true and 'patchMode' must + be set to 'AutomaticByPlatform'. + :vartype enable_hotpatching: bool + :ivar assessment_mode: Specifies the mode of VM Guest patch assessment for the IaaS virtual + machine.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` + **ImageDefault** - You control the timing of patch assessments on a virtual machine.:code:`
`:code:`
` **AutomaticByPlatform** - The platform will trigger periodic patch + assessments. The property provisionVMAgent must be true. Known values are: "ImageDefault" and + "AutomaticByPlatform". + :vartype assessment_mode: str or ~azure.mgmt.computefleet.models.WindowsPatchAssessmentMode + :ivar automatic_by_platform_settings: Specifies additional settings for patch mode + AutomaticByPlatform in VM Guest Patching on Windows. + :vartype automatic_by_platform_settings: + ~azure.mgmt.computefleet.models.WindowsVMGuestPatchAutomaticByPlatformSettings + """ + + _attribute_map = { + "patch_mode": {"key": "patchMode", "type": "str"}, + "enable_hotpatching": {"key": "enableHotpatching", "type": "bool"}, + "assessment_mode": {"key": "assessmentMode", "type": "str"}, + "automatic_by_platform_settings": { + "key": "automaticByPlatformSettings", + "type": "WindowsVMGuestPatchAutomaticByPlatformSettings", + }, + } + + def __init__( + self, + *, + patch_mode: Optional[Union[str, "_models.WindowsVMGuestPatchMode"]] = None, + enable_hotpatching: Optional[bool] = None, + assessment_mode: Optional[Union[str, "_models.WindowsPatchAssessmentMode"]] = None, + automatic_by_platform_settings: Optional["_models.WindowsVMGuestPatchAutomaticByPlatformSettings"] = None, + **kwargs: Any + ) -> None: + """ + :keyword patch_mode: Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual + machines associated to virtual machine scale set with OrchestrationMode as Flexible.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` **Manual** - You control + the application of patches to a virtual machine. You do this by applying patches manually + inside the VM. In this mode, automatic updates are disabled; the property + WindowsConfiguration.enableAutomaticUpdates must be false:code:`
`:code:`
` + **AutomaticByOS** - The virtual machine will automatically be updated by the OS. The property + WindowsConfiguration.enableAutomaticUpdates must be true. :code:`
`:code:`
` + **AutomaticByPlatform** - the virtual machine will automatically updated by the platform. The + properties provisionVMAgent and WindowsConfiguration.enableAutomaticUpdates must be true. Known + values are: "Manual", "AutomaticByOS", and "AutomaticByPlatform". + :paramtype patch_mode: str or ~azure.mgmt.computefleet.models.WindowsVMGuestPatchMode + :keyword enable_hotpatching: Enables customers to patch their Azure VMs without requiring a + reboot. For enableHotpatching, the 'provisionVMAgent' must be set to true and 'patchMode' must + be set to 'AutomaticByPlatform'. + :paramtype enable_hotpatching: bool + :keyword assessment_mode: Specifies the mode of VM Guest patch assessment for the IaaS virtual + machine.:code:`
`:code:`
` Possible values are::code:`
`:code:`
` + **ImageDefault** - You control the timing of patch assessments on a virtual machine.:code:`
`:code:`
` **AutomaticByPlatform** - The platform will trigger periodic patch + assessments. The property provisionVMAgent must be true. Known values are: "ImageDefault" and + "AutomaticByPlatform". + :paramtype assessment_mode: str or ~azure.mgmt.computefleet.models.WindowsPatchAssessmentMode + :keyword automatic_by_platform_settings: Specifies additional settings for patch mode + AutomaticByPlatform in VM Guest Patching on Windows. + :paramtype automatic_by_platform_settings: + ~azure.mgmt.computefleet.models.WindowsVMGuestPatchAutomaticByPlatformSettings + """ + super().__init__(**kwargs) + self.patch_mode = patch_mode + self.enable_hotpatching = enable_hotpatching + self.assessment_mode = assessment_mode + self.automatic_by_platform_settings = automatic_by_platform_settings + + +class Plan(_serialization.Model): + """Plan for the resource. + + All required parameters must be populated in order to send to server. + + :ivar name: A user defined name of the 3rd Party Artifact that is being procured. Required. + :vartype name: str + :ivar publisher: The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. + Required. + :vartype publisher: str + :ivar product: The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to + the OfferID specified for the artifact at the time of Data Market onboarding. Required. + :vartype product: str + :ivar promotion_code: A publisher provided promotion code as provisioned in Data Market for the + said product/artifact. + :vartype promotion_code: str + :ivar version: The version of the desired product/artifact. + :vartype version: str + """ + + _validation = { + "name": {"required": True}, + "publisher": {"required": True}, + "product": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "product": {"key": "product", "type": "str"}, + "promotion_code": {"key": "promotionCode", "type": "str"}, + "version": {"key": "version", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + publisher: str, + product: str, + promotion_code: Optional[str] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: A user defined name of the 3rd Party Artifact that is being procured. Required. + :paramtype name: str + :keyword publisher: The publisher of the 3rd Party Artifact that is being bought. E.g. + NewRelic. Required. + :paramtype publisher: str + :keyword product: The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to + the OfferID specified for the artifact at the time of Data Market onboarding. Required. + :paramtype product: str + :keyword promotion_code: A publisher provided promotion code as provisioned in Data Market for + the said product/artifact. + :paramtype promotion_code: str + :keyword version: The version of the desired product/artifact. + :paramtype version: str + """ + super().__init__(**kwargs) + self.name = name + self.publisher = publisher + self.product = product + self.promotion_code = promotion_code + self.version = version + + +class ProxyAgentSettings(_serialization.Model): + """Specifies ProxyAgent settings while creating the virtual machine. Minimum api-version: + 2023-09-01. + + :ivar enabled: Specifies whether ProxyAgent feature should be enabled on the virtual machine or + virtual machine scale set. + :vartype enabled: bool + :ivar mode: Specifies the mode that ProxyAgent will execute on if the feature is enabled. + ProxyAgent will start to audit or monitor but not enforce access control over requests to host + endpoints in Audit mode, while in Enforce mode it will enforce access control. The default + value is Enforce mode. Known values are: "Audit" and "Enforce". + :vartype mode: str or ~azure.mgmt.computefleet.models.Mode + :ivar key_incarnation_id: Increase the value of this property allows user to reset the key used + for securing communication channel between guest and host. + :vartype key_incarnation_id: int + """ + + _attribute_map = { + "enabled": {"key": "enabled", "type": "bool"}, + "mode": {"key": "mode", "type": "str"}, + "key_incarnation_id": {"key": "keyIncarnationId", "type": "int"}, + } + + def __init__( + self, + *, + enabled: Optional[bool] = None, + mode: Optional[Union[str, "_models.Mode"]] = None, + key_incarnation_id: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword enabled: Specifies whether ProxyAgent feature should be enabled on the virtual machine + or virtual machine scale set. + :paramtype enabled: bool + :keyword mode: Specifies the mode that ProxyAgent will execute on if the feature is enabled. + ProxyAgent will start to audit or monitor but not enforce access control over requests to host + endpoints in Audit mode, while in Enforce mode it will enforce access control. The default + value is Enforce mode. Known values are: "Audit" and "Enforce". + :paramtype mode: str or ~azure.mgmt.computefleet.models.Mode + :keyword key_incarnation_id: Increase the value of this property allows user to reset the key + used for securing communication channel between guest and host. + :paramtype key_incarnation_id: int + """ + super().__init__(**kwargs) + self.enabled = enabled + self.mode = mode + self.key_incarnation_id = key_incarnation_id + + +class PublicIPAddressSku(_serialization.Model): + """Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible. + + :ivar name: Specify public IP sku name. Known values are: "Basic" and "Standard". + :vartype name: str or ~azure.mgmt.computefleet.models.PublicIPAddressSkuName + :ivar tier: Specify public IP sku tier. Known values are: "Regional" and "Global". + :vartype tier: str or ~azure.mgmt.computefleet.models.PublicIPAddressSkuTier + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[Union[str, "_models.PublicIPAddressSkuName"]] = None, + tier: Optional[Union[str, "_models.PublicIPAddressSkuTier"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Specify public IP sku name. Known values are: "Basic" and "Standard". + :paramtype name: str or ~azure.mgmt.computefleet.models.PublicIPAddressSkuName + :keyword tier: Specify public IP sku tier. Known values are: "Regional" and "Global". + :paramtype tier: str or ~azure.mgmt.computefleet.models.PublicIPAddressSkuTier + """ + super().__init__(**kwargs) + self.name = name + self.tier = tier + + +class RegularPriorityProfile(_serialization.Model): + """Configuration Options for Regular instances in Compute Fleet. + + :ivar capacity: Total capacity to achieve. It is currently in terms of number of VMs. + :vartype capacity: int + :ivar min_capacity: Minimum capacity to achieve which cannot be updated. If we will not be able + to "guarantee" minimum capacity, we will reject the request in the sync path itself. + :vartype min_capacity: int + :ivar allocation_strategy: Allocation strategy to follow when determining the VM sizes + distribution for Regular VMs. Known values are: "LowestPrice" and "Prioritized". + :vartype allocation_strategy: str or + ~azure.mgmt.computefleet.models.RegularPriorityAllocationStrategy + """ + + _validation = { + "capacity": {"minimum": 0}, + "min_capacity": {"minimum": 0}, + } + + _attribute_map = { + "capacity": {"key": "capacity", "type": "int"}, + "min_capacity": {"key": "minCapacity", "type": "int"}, + "allocation_strategy": {"key": "allocationStrategy", "type": "str"}, + } + + def __init__( + self, + *, + capacity: Optional[int] = None, + min_capacity: Optional[int] = None, + allocation_strategy: Optional[Union[str, "_models.RegularPriorityAllocationStrategy"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword capacity: Total capacity to achieve. It is currently in terms of number of VMs. + :paramtype capacity: int + :keyword min_capacity: Minimum capacity to achieve which cannot be updated. If we will not be + able to "guarantee" minimum capacity, we will reject the request in the sync path itself. + :paramtype min_capacity: int + :keyword allocation_strategy: Allocation strategy to follow when determining the VM sizes + distribution for Regular VMs. Known values are: "LowestPrice" and "Prioritized". + :paramtype allocation_strategy: str or + ~azure.mgmt.computefleet.models.RegularPriorityAllocationStrategy + """ + super().__init__(**kwargs) + self.capacity = capacity + self.min_capacity = min_capacity + self.allocation_strategy = allocation_strategy + + +class ResourcePlanUpdate(_serialization.Model): + """The template for adding optional properties. + + :ivar name: A user defined name of the 3rd Party Artifact that is being procured. + :vartype name: str + :ivar publisher: The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. + :vartype publisher: str + :ivar product: The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to + the OfferID specified for the artifact at the time of Data Market onboarding. + :vartype product: str + :ivar promotion_code: A publisher provided promotion code as provisioned in Data Market for the + said product/artifact. + :vartype promotion_code: str + :ivar version: The version of the desired product/artifact. + :vartype version: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "publisher": {"key": "publisher", "type": "str"}, + "product": {"key": "product", "type": "str"}, + "promotion_code": {"key": "promotionCode", "type": "str"}, + "version": {"key": "version", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + publisher: Optional[str] = None, + product: Optional[str] = None, + promotion_code: Optional[str] = None, + version: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: A user defined name of the 3rd Party Artifact that is being procured. + :paramtype name: str + :keyword publisher: The publisher of the 3rd Party Artifact that is being bought. E.g. + NewRelic. + :paramtype publisher: str + :keyword product: The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to + the OfferID specified for the artifact at the time of Data Market onboarding. + :paramtype product: str + :keyword promotion_code: A publisher provided promotion code as provisioned in Data Market for + the said product/artifact. + :paramtype promotion_code: str + :keyword version: The version of the desired product/artifact. + :paramtype version: str + """ + super().__init__(**kwargs) + self.name = name + self.publisher = publisher + self.product = product + self.promotion_code = promotion_code + self.version = version + + +class ResourceWithOptionalLocation(_serialization.Model): + """The Resource model definition with location property as optional. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar location: Resource location. + :vartype location: str + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.location = location + self.id = None + self.name = None + self.type = None + self.tags = tags + + +class ScheduledEventsProfile(_serialization.Model): + """ScheduledEventsProfile. + + :ivar terminate_notification_profile: Specifies Terminate Scheduled Event related + configurations. + :vartype terminate_notification_profile: + ~azure.mgmt.computefleet.models.TerminateNotificationProfile + :ivar os_image_notification_profile: Specifies OS Image Scheduled Event related configurations. + :vartype os_image_notification_profile: + ~azure.mgmt.computefleet.models.OSImageNotificationProfile + """ + + _attribute_map = { + "terminate_notification_profile": { + "key": "terminateNotificationProfile", + "type": "TerminateNotificationProfile", + }, + "os_image_notification_profile": {"key": "osImageNotificationProfile", "type": "OSImageNotificationProfile"}, + } + + def __init__( + self, + *, + terminate_notification_profile: Optional["_models.TerminateNotificationProfile"] = None, + os_image_notification_profile: Optional["_models.OSImageNotificationProfile"] = None, + **kwargs: Any + ) -> None: + """ + :keyword terminate_notification_profile: Specifies Terminate Scheduled Event related + configurations. + :paramtype terminate_notification_profile: + ~azure.mgmt.computefleet.models.TerminateNotificationProfile + :keyword os_image_notification_profile: Specifies OS Image Scheduled Event related + configurations. + :paramtype os_image_notification_profile: + ~azure.mgmt.computefleet.models.OSImageNotificationProfile + """ + super().__init__(**kwargs) + self.terminate_notification_profile = terminate_notification_profile + self.os_image_notification_profile = os_image_notification_profile + + +class SecurityPostureReference(_serialization.Model): + """Specifies the security posture to be used for all virtual machines in the scale set. Minimum + api-version: 2023-03-01. + + :ivar id: The security posture reference id in the form of + /CommunityGalleries/{communityGalleryName}/securityPostures/{securityPostureName}/versions/{major.minor.patch}|{major.*}|latest. # pylint: disable=line-too-long + :vartype id: str + :ivar exclude_extensions: List of virtual machine extensions to exclude when applying the + Security Posture. + :vartype exclude_extensions: list[~azure.mgmt.computefleet.models.VirtualMachineExtension] + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "exclude_extensions": {"key": "excludeExtensions", "type": "[VirtualMachineExtension]"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + exclude_extensions: Optional[List["_models.VirtualMachineExtension"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The security posture reference id in the form of + /CommunityGalleries/{communityGalleryName}/securityPostures/{securityPostureName}/versions/{major.minor.patch}|{major.*}|latest. # pylint: disable=line-too-long + :paramtype id: str + :keyword exclude_extensions: List of virtual machine extensions to exclude when applying the + Security Posture. + :paramtype exclude_extensions: list[~azure.mgmt.computefleet.models.VirtualMachineExtension] + """ + super().__init__(**kwargs) + self.id = id + self.exclude_extensions = exclude_extensions + + +class SecurityProfile(_serialization.Model): + """Specifies the Security profile settings for the virtual machine or virtual machine scale set. + + :ivar uefi_settings: Specifies the security settings like secure boot and vTPM used while + creating the virtual machine. Minimum api-version: 2020-12-01. + :vartype uefi_settings: ~azure.mgmt.computefleet.models.UefiSettings + :ivar encryption_at_host: This property can be used by user in the request to enable or disable + the Host Encryption for the virtual machine or virtual machine scale set. This will enable the + encryption for all the disks including Resource/Temp disk at host itself. The default behavior + is: The Encryption at host will be disabled unless this property is set to true for the + resource. + :vartype encryption_at_host: bool + :ivar security_type: Specifies the SecurityType of the virtual machine. It has to be set to any + specified value to enable UefiSettings. The default behavior is: UefiSettings will not be + enabled unless this property is set. Known values are: "TrustedLaunch" and "ConfidentialVM". + :vartype security_type: str or ~azure.mgmt.computefleet.models.SecurityTypes + :ivar encryption_identity: Specifies the Managed Identity used by ADE to get access token for + keyvault operations. + :vartype encryption_identity: ~azure.mgmt.computefleet.models.EncryptionIdentity + :ivar proxy_agent_settings: Specifies ProxyAgent settings while creating the virtual machine. + Minimum api-version: 2023-09-01. + :vartype proxy_agent_settings: ~azure.mgmt.computefleet.models.ProxyAgentSettings + """ + + _attribute_map = { + "uefi_settings": {"key": "uefiSettings", "type": "UefiSettings"}, + "encryption_at_host": {"key": "encryptionAtHost", "type": "bool"}, + "security_type": {"key": "securityType", "type": "str"}, + "encryption_identity": {"key": "encryptionIdentity", "type": "EncryptionIdentity"}, + "proxy_agent_settings": {"key": "proxyAgentSettings", "type": "ProxyAgentSettings"}, + } + + def __init__( + self, + *, + uefi_settings: Optional["_models.UefiSettings"] = None, + encryption_at_host: Optional[bool] = None, + security_type: Optional[Union[str, "_models.SecurityTypes"]] = None, + encryption_identity: Optional["_models.EncryptionIdentity"] = None, + proxy_agent_settings: Optional["_models.ProxyAgentSettings"] = None, + **kwargs: Any + ) -> None: + """ + :keyword uefi_settings: Specifies the security settings like secure boot and vTPM used while + creating the virtual machine. Minimum api-version: 2020-12-01. + :paramtype uefi_settings: ~azure.mgmt.computefleet.models.UefiSettings + :keyword encryption_at_host: This property can be used by user in the request to enable or + disable the Host Encryption for the virtual machine or virtual machine scale set. This will + enable the encryption for all the disks including Resource/Temp disk at host itself. The + default behavior is: The Encryption at host will be disabled unless this property is set to + true for the resource. + :paramtype encryption_at_host: bool + :keyword security_type: Specifies the SecurityType of the virtual machine. It has to be set to + any specified value to enable UefiSettings. The default behavior is: UefiSettings will not be + enabled unless this property is set. Known values are: "TrustedLaunch" and "ConfidentialVM". + :paramtype security_type: str or ~azure.mgmt.computefleet.models.SecurityTypes + :keyword encryption_identity: Specifies the Managed Identity used by ADE to get access token + for keyvault operations. + :paramtype encryption_identity: ~azure.mgmt.computefleet.models.EncryptionIdentity + :keyword proxy_agent_settings: Specifies ProxyAgent settings while creating the virtual + machine. Minimum api-version: 2023-09-01. + :paramtype proxy_agent_settings: ~azure.mgmt.computefleet.models.ProxyAgentSettings + """ + super().__init__(**kwargs) + self.uefi_settings = uefi_settings + self.encryption_at_host = encryption_at_host + self.security_type = security_type + self.encryption_identity = encryption_identity + self.proxy_agent_settings = proxy_agent_settings + + +class ServiceArtifactReference(_serialization.Model): + """Specifies the service artifact reference id used to set same image version for all virtual + machines in the scale set when using 'latest' image version. Minimum api-version: 2022-11-01. + + :ivar id: The service artifact reference id in the form of + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName}. # pylint: disable=line-too-long + :vartype id: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, id: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword id: The service artifact reference id in the form of + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName}. # pylint: disable=line-too-long + :paramtype id: str + """ + super().__init__(**kwargs) + self.id = id + + +class SpotPriorityProfile(_serialization.Model): + """Configuration Options for Spot instances in Compute Fleet. + + :ivar capacity: Total capacity to achieve. It is currently in terms of number of VMs. + :vartype capacity: int + :ivar min_capacity: Minimum capacity to achieve which cannot be updated. If we will not be able + to "guarantee" minimum capacity, we will reject the request in the sync path itself. + :vartype min_capacity: int + :ivar max_price_per_vm: Price per hour of each Spot VM will never exceed this. + :vartype max_price_per_vm: float + :ivar eviction_policy: Eviction Policy to follow when evicting Spot VMs. Known values are: + "Delete" and "Deallocate". + :vartype eviction_policy: str or ~azure.mgmt.computefleet.models.EvictionPolicy + :ivar allocation_strategy: Allocation strategy to follow when determining the VM sizes + distribution for Spot VMs. Known values are: "PriceCapacityOptimized", "LowestPrice", and + "CapacityOptimized". + :vartype allocation_strategy: str or ~azure.mgmt.computefleet.models.SpotAllocationStrategy + :ivar maintain: Flag to enable/disable continuous goal seeking for the desired capacity and + restoration of evicted Spot VMs. + If maintain is enabled, AzureFleetRP will use all VM sizes in vmSizesProfile to create new VMs + (if VMs are evicted deleted) + or update existing VMs with new VM sizes (if VMs are evicted deallocated or failed to allocate + due to capacity constraint) in order to achieve the desired capacity. + Maintain is enabled by default. + :vartype maintain: bool + """ + + _validation = { + "capacity": {"minimum": 0}, + "min_capacity": {"minimum": 0}, + } + + _attribute_map = { + "capacity": {"key": "capacity", "type": "int"}, + "min_capacity": {"key": "minCapacity", "type": "int"}, + "max_price_per_vm": {"key": "maxPricePerVM", "type": "float"}, + "eviction_policy": {"key": "evictionPolicy", "type": "str"}, + "allocation_strategy": {"key": "allocationStrategy", "type": "str"}, + "maintain": {"key": "maintain", "type": "bool"}, + } + + def __init__( + self, + *, + capacity: Optional[int] = None, + min_capacity: Optional[int] = None, + max_price_per_vm: Optional[float] = None, + eviction_policy: Optional[Union[str, "_models.EvictionPolicy"]] = None, + allocation_strategy: Optional[Union[str, "_models.SpotAllocationStrategy"]] = None, + maintain: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword capacity: Total capacity to achieve. It is currently in terms of number of VMs. + :paramtype capacity: int + :keyword min_capacity: Minimum capacity to achieve which cannot be updated. If we will not be + able to "guarantee" minimum capacity, we will reject the request in the sync path itself. + :paramtype min_capacity: int + :keyword max_price_per_vm: Price per hour of each Spot VM will never exceed this. + :paramtype max_price_per_vm: float + :keyword eviction_policy: Eviction Policy to follow when evicting Spot VMs. Known values are: + "Delete" and "Deallocate". + :paramtype eviction_policy: str or ~azure.mgmt.computefleet.models.EvictionPolicy + :keyword allocation_strategy: Allocation strategy to follow when determining the VM sizes + distribution for Spot VMs. Known values are: "PriceCapacityOptimized", "LowestPrice", and + "CapacityOptimized". + :paramtype allocation_strategy: str or ~azure.mgmt.computefleet.models.SpotAllocationStrategy + :keyword maintain: Flag to enable/disable continuous goal seeking for the desired capacity and + restoration of evicted Spot VMs. + If maintain is enabled, AzureFleetRP will use all VM sizes in vmSizesProfile to create new VMs + (if VMs are evicted deleted) + or update existing VMs with new VM sizes (if VMs are evicted deallocated or failed to allocate + due to capacity constraint) in order to achieve the desired capacity. + Maintain is enabled by default. + :paramtype maintain: bool + """ + super().__init__(**kwargs) + self.capacity = capacity + self.min_capacity = min_capacity + self.max_price_per_vm = max_price_per_vm + self.eviction_policy = eviction_policy + self.allocation_strategy = allocation_strategy + self.maintain = maintain + + +class SshConfiguration(_serialization.Model): + """SSH configuration for Linux based VMs running on Azure. + + :ivar public_keys: The list of SSH public keys used to authenticate with linux based VMs. + :vartype public_keys: list[~azure.mgmt.computefleet.models.SshPublicKey] + """ + + _attribute_map = { + "public_keys": {"key": "publicKeys", "type": "[SshPublicKey]"}, + } + + def __init__(self, *, public_keys: Optional[List["_models.SshPublicKey"]] = None, **kwargs: Any) -> None: + """ + :keyword public_keys: The list of SSH public keys used to authenticate with linux based VMs. + :paramtype public_keys: list[~azure.mgmt.computefleet.models.SshPublicKey] + """ + super().__init__(**kwargs) + self.public_keys = public_keys + + +class SshPublicKey(_serialization.Model): + """Contains information about SSH certificate public key and the path on the Linux VM where the + public key is placed. + + :ivar path: Specifies the full path on the created VM where ssh public key is stored. If the + file already exists, the specified key is appended to the file. Example: + /home/user/.ssh/authorized_keys. + :vartype path: str + :ivar key_data: SSH public key certificate used to authenticate with the VM through ssh. The + key needs to be at least 2048-bit and in ssh-rsa format. For creating ssh keys, see [Create SSH + keys on Linux and Mac for Linux VMs in + Azure]https://docs.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed). + :vartype key_data: str + """ + + _attribute_map = { + "path": {"key": "path", "type": "str"}, + "key_data": {"key": "keyData", "type": "str"}, + } + + def __init__(self, *, path: Optional[str] = None, key_data: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword path: Specifies the full path on the created VM where ssh public key is stored. If the + file already exists, the specified key is appended to the file. Example: + /home/user/.ssh/authorized_keys. + :paramtype path: str + :keyword key_data: SSH public key certificate used to authenticate with the VM through ssh. The + key needs to be at least 2048-bit and in ssh-rsa format. For creating ssh keys, see [Create SSH + keys on Linux and Mac for Linux VMs in + Azure]https://docs.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed). + :paramtype key_data: str + """ + super().__init__(**kwargs) + self.path = path + self.key_data = key_data + + +class SubResourceReadOnly(_serialization.Model): + """SubResourceReadOnly. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + """ + + _validation = { + "id": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.computefleet.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.computefleet.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.computefleet.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or ~azure.mgmt.computefleet.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class TerminateNotificationProfile(_serialization.Model): + """TerminateNotificationProfile. + + :ivar not_before_timeout: Configurable length of time a Virtual Machine being deleted will have + to potentially approve the Terminate Scheduled Event before the event is auto approved (timed + out). The configuration must be specified in ISO 8601 format, the default value is 5 minutes + (PT5M). + :vartype not_before_timeout: str + :ivar enable: Specifies whether the Terminate Scheduled event is enabled or disabled. + :vartype enable: bool + """ + + _attribute_map = { + "not_before_timeout": {"key": "notBeforeTimeout", "type": "str"}, + "enable": {"key": "enable", "type": "bool"}, + } + + def __init__( + self, *, not_before_timeout: Optional[str] = None, enable: Optional[bool] = None, **kwargs: Any + ) -> None: + """ + :keyword not_before_timeout: Configurable length of time a Virtual Machine being deleted will + have to potentially approve the Terminate Scheduled Event before the event is auto approved + (timed out). The configuration must be specified in ISO 8601 format, the default value is 5 + minutes (PT5M). + :paramtype not_before_timeout: str + :keyword enable: Specifies whether the Terminate Scheduled event is enabled or disabled. + :paramtype enable: bool + """ + super().__init__(**kwargs) + self.not_before_timeout = not_before_timeout + self.enable = enable + + +class UefiSettings(_serialization.Model): + """Specifies the security settings like secure boot and vTPM used while creating the virtual + machine. Minimum api-version: 2020-12-01. + + :ivar secure_boot_enabled: Specifies whether secure boot should be enabled on the virtual + machine. Minimum api-version: 2020-12-01. + :vartype secure_boot_enabled: bool + :ivar v_tpm_enabled: Specifies whether vTPM should be enabled on the virtual machine. Minimum + api-version: 2020-12-01. + :vartype v_tpm_enabled: bool + """ + + _attribute_map = { + "secure_boot_enabled": {"key": "secureBootEnabled", "type": "bool"}, + "v_tpm_enabled": {"key": "vTpmEnabled", "type": "bool"}, + } + + def __init__( + self, *, secure_boot_enabled: Optional[bool] = None, v_tpm_enabled: Optional[bool] = None, **kwargs: Any + ) -> None: + """ + :keyword secure_boot_enabled: Specifies whether secure boot should be enabled on the virtual + machine. Minimum api-version: 2020-12-01. + :paramtype secure_boot_enabled: bool + :keyword v_tpm_enabled: Specifies whether vTPM should be enabled on the virtual machine. + Minimum api-version: 2020-12-01. + :paramtype v_tpm_enabled: bool + """ + super().__init__(**kwargs) + self.secure_boot_enabled = secure_boot_enabled + self.v_tpm_enabled = v_tpm_enabled + + +class UserAssignedIdentity(_serialization.Model): + """User assigned identity properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of the assigned identity. + :vartype principal_id: str + :ivar client_id: The client ID of the assigned identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id = None + self.client_id = None + + +class VaultCertificate(_serialization.Model): + """Describes a single certificate reference in a Key Vault, and where the certificate should + reside on the VM. + + :ivar certificate_url: This is the URL of a certificate that has been uploaded to Key Vault as + a secret. For adding a secret to the Key Vault, see `Add a key or secret to the key vault + `_. In this case, your + certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded + in UTF-8: :code:`
`:code:`
` {:code:`
` + "data":":code:``",:code:`
` "dataType":"pfx",:code:`
` + "password":":code:``":code:`
`} :code:`
` To install certificates on a + virtual machine it is recommended to use the `Azure Key Vault virtual machine extension for + Linux `_ or the + `Azure Key Vault virtual machine extension for Windows + `_. + :vartype certificate_url: str + :ivar certificate_store: For Windows VMs, specifies the certificate store on the Virtual + Machine to which the certificate should be added. The specified certificate store is implicitly + in the LocalMachine account. For Linux VMs, the certificate file is placed under the + /var/lib/waagent directory, with the file name <UppercaseThumbprint>.crt for the X509 + certificate file and <UppercaseThumbprint>.prv for private key. Both of these files are + .pem formatted. + :vartype certificate_store: str + """ + + _attribute_map = { + "certificate_url": {"key": "certificateUrl", "type": "str"}, + "certificate_store": {"key": "certificateStore", "type": "str"}, + } + + def __init__( + self, *, certificate_url: Optional[str] = None, certificate_store: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword certificate_url: This is the URL of a certificate that has been uploaded to Key Vault + as a secret. For adding a secret to the Key Vault, see `Add a key or secret to the key vault + `_. In this case, your + certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded + in UTF-8: :code:`
`:code:`
` {:code:`
` + "data":":code:``",:code:`
` "dataType":"pfx",:code:`
` + "password":":code:``":code:`
`} :code:`
` To install certificates on a + virtual machine it is recommended to use the `Azure Key Vault virtual machine extension for + Linux `_ or the + `Azure Key Vault virtual machine extension for Windows + `_. + :paramtype certificate_url: str + :keyword certificate_store: For Windows VMs, specifies the certificate store on the Virtual + Machine to which the certificate should be added. The specified certificate store is implicitly + in the LocalMachine account. For Linux VMs, the certificate file is placed under the + /var/lib/waagent directory, with the file name <UppercaseThumbprint>.crt for the X509 + certificate file and <UppercaseThumbprint>.prv for private key. Both of these files are + .pem formatted. + :paramtype certificate_store: str + """ + super().__init__(**kwargs) + self.certificate_url = certificate_url + self.certificate_store = certificate_store + + +class VaultSecretGroup(_serialization.Model): + """Describes a set of certificates which are all in the same Key Vault. + + :ivar source_vault: The relative URL of the Key Vault containing all of the certificates in + VaultCertificates. + :vartype source_vault: ~azure.mgmt.computefleet.models.SubResource + :ivar vault_certificates: The list of key vault references in SourceVault which contain + certificates. + :vartype vault_certificates: list[~azure.mgmt.computefleet.models.VaultCertificate] + """ + + _attribute_map = { + "source_vault": {"key": "sourceVault", "type": "SubResource"}, + "vault_certificates": {"key": "vaultCertificates", "type": "[VaultCertificate]"}, + } + + def __init__( + self, + *, + source_vault: Optional["_models.SubResource"] = None, + vault_certificates: Optional[List["_models.VaultCertificate"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword source_vault: The relative URL of the Key Vault containing all of the certificates in + VaultCertificates. + :paramtype source_vault: ~azure.mgmt.computefleet.models.SubResource + :keyword vault_certificates: The list of key vault references in SourceVault which contain + certificates. + :paramtype vault_certificates: list[~azure.mgmt.computefleet.models.VaultCertificate] + """ + super().__init__(**kwargs) + self.source_vault = source_vault + self.vault_certificates = vault_certificates + + +class VirtualHardDisk(_serialization.Model): + """Describes the uri of a disk. + + :ivar uri: Specifies the virtual hard disk's uri. + :vartype uri: str + """ + + _attribute_map = { + "uri": {"key": "uri", "type": "str"}, + } + + def __init__(self, *, uri: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword uri: Specifies the virtual hard disk's uri. + :paramtype uri: str + """ + super().__init__(**kwargs) + self.uri = uri + + +class VirtualMachineExtension(ResourceWithOptionalLocation): # pylint: disable=too-many-instance-attributes + """Describes a Virtual Machine Extension. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar location: Resource location. + :vartype location: str + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar force_update_tag: How the extension handler should be forced to update even if the + extension configuration has not changed. + :vartype force_update_tag: str + :ivar publisher: The name of the extension handler publisher. + :vartype publisher: str + :ivar type_properties_type: Specifies the type of the extension; an example is + "CustomScriptExtension". + :vartype type_properties_type: str + :ivar type_handler_version: Specifies the version of the script handler. + :vartype type_handler_version: str + :ivar auto_upgrade_minor_version: Indicates whether the extension should use a newer minor + version if one is available at deployment time. Once deployed, however, the extension will not + upgrade minor versions unless redeployed, even with this property set to true. + :vartype auto_upgrade_minor_version: bool + :ivar enable_automatic_upgrade: Indicates whether the extension should be automatically + upgraded by the platform if there is a newer version of the extension available. + :vartype enable_automatic_upgrade: bool + :ivar settings: Json formatted public settings for the extension. + :vartype settings: JSON + :ivar protected_settings: The extension can contain either protectedSettings or + protectedSettingsFromKeyVault or no protected settings at all. + :vartype protected_settings: JSON + :ivar provisioning_state: The provisioning state, which only appears in the response. + :vartype provisioning_state: str + :ivar instance_view: The virtual machine extension instance view. + :vartype instance_view: ~azure.mgmt.computefleet.models.VirtualMachineExtensionInstanceView + :ivar suppress_failures: Indicates whether failures stemming from the extension will be + suppressed (Operational failures such as not connecting to the VM will not be suppressed + regardless of this value). The default is false. + :vartype suppress_failures: bool + :ivar protected_settings_from_key_vault: The extensions protected settings that are passed by + reference, and consumed from key vault. + :vartype protected_settings_from_key_vault: + ~azure.mgmt.computefleet.models.KeyVaultSecretReference + :ivar provision_after_extensions: Collection of extension names after which this extension + needs to be provisioned. + :vartype provision_after_extensions: list[str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "force_update_tag": {"key": "properties.forceUpdateTag", "type": "str"}, + "publisher": {"key": "properties.publisher", "type": "str"}, + "type_properties_type": {"key": "properties.type", "type": "str"}, + "type_handler_version": {"key": "properties.typeHandlerVersion", "type": "str"}, + "auto_upgrade_minor_version": {"key": "properties.autoUpgradeMinorVersion", "type": "bool"}, + "enable_automatic_upgrade": {"key": "properties.enableAutomaticUpgrade", "type": "bool"}, + "settings": {"key": "properties.settings", "type": "object"}, + "protected_settings": {"key": "properties.protectedSettings", "type": "object"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "instance_view": {"key": "properties.instanceView", "type": "VirtualMachineExtensionInstanceView"}, + "suppress_failures": {"key": "properties.suppressFailures", "type": "bool"}, + "protected_settings_from_key_vault": { + "key": "properties.protectedSettingsFromKeyVault", + "type": "KeyVaultSecretReference", + }, + "provision_after_extensions": {"key": "properties.provisionAfterExtensions", "type": "[str]"}, + } + + def __init__( + self, + *, + location: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + force_update_tag: Optional[str] = None, + publisher: Optional[str] = None, + type_properties_type: Optional[str] = None, + type_handler_version: Optional[str] = None, + auto_upgrade_minor_version: Optional[bool] = None, + enable_automatic_upgrade: Optional[bool] = None, + settings: Optional[JSON] = None, + protected_settings: Optional[JSON] = None, + instance_view: Optional["_models.VirtualMachineExtensionInstanceView"] = None, + suppress_failures: Optional[bool] = None, + protected_settings_from_key_vault: Optional["_models.KeyVaultSecretReference"] = None, + provision_after_extensions: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword force_update_tag: How the extension handler should be forced to update even if the + extension configuration has not changed. + :paramtype force_update_tag: str + :keyword publisher: The name of the extension handler publisher. + :paramtype publisher: str + :keyword type_properties_type: Specifies the type of the extension; an example is + "CustomScriptExtension". + :paramtype type_properties_type: str + :keyword type_handler_version: Specifies the version of the script handler. + :paramtype type_handler_version: str + :keyword auto_upgrade_minor_version: Indicates whether the extension should use a newer minor + version if one is available at deployment time. Once deployed, however, the extension will not + upgrade minor versions unless redeployed, even with this property set to true. + :paramtype auto_upgrade_minor_version: bool + :keyword enable_automatic_upgrade: Indicates whether the extension should be automatically + upgraded by the platform if there is a newer version of the extension available. + :paramtype enable_automatic_upgrade: bool + :keyword settings: Json formatted public settings for the extension. + :paramtype settings: JSON + :keyword protected_settings: The extension can contain either protectedSettings or + protectedSettingsFromKeyVault or no protected settings at all. + :paramtype protected_settings: JSON + :keyword instance_view: The virtual machine extension instance view. + :paramtype instance_view: ~azure.mgmt.computefleet.models.VirtualMachineExtensionInstanceView + :keyword suppress_failures: Indicates whether failures stemming from the extension will be + suppressed (Operational failures such as not connecting to the VM will not be suppressed + regardless of this value). The default is false. + :paramtype suppress_failures: bool + :keyword protected_settings_from_key_vault: The extensions protected settings that are passed + by reference, and consumed from key vault. + :paramtype protected_settings_from_key_vault: + ~azure.mgmt.computefleet.models.KeyVaultSecretReference + :keyword provision_after_extensions: Collection of extension names after which this extension + needs to be provisioned. + :paramtype provision_after_extensions: list[str] + """ + super().__init__(location=location, tags=tags, **kwargs) + self.force_update_tag = force_update_tag + self.publisher = publisher + self.type_properties_type = type_properties_type + self.type_handler_version = type_handler_version + self.auto_upgrade_minor_version = auto_upgrade_minor_version + self.enable_automatic_upgrade = enable_automatic_upgrade + self.settings = settings + self.protected_settings = protected_settings + self.provisioning_state = None + self.instance_view = instance_view + self.suppress_failures = suppress_failures + self.protected_settings_from_key_vault = protected_settings_from_key_vault + self.provision_after_extensions = provision_after_extensions + + +class VirtualMachineExtensionInstanceView(_serialization.Model): + """The instance view of a virtual machine extension. + + :ivar name: The virtual machine extension name. + :vartype name: str + :ivar type: Specifies the type of the extension; an example is "CustomScriptExtension". + :vartype type: str + :ivar type_handler_version: Specifies the version of the script handler. + :vartype type_handler_version: str + :ivar substatuses: The resource status information. + :vartype substatuses: list[~azure.mgmt.computefleet.models.InstanceViewStatus] + :ivar statuses: The resource status information. + :vartype statuses: list[~azure.mgmt.computefleet.models.InstanceViewStatus] + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "type_handler_version": {"key": "typeHandlerVersion", "type": "str"}, + "substatuses": {"key": "substatuses", "type": "[InstanceViewStatus]"}, + "statuses": {"key": "statuses", "type": "[InstanceViewStatus]"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + type: Optional[str] = None, + type_handler_version: Optional[str] = None, + substatuses: Optional[List["_models.InstanceViewStatus"]] = None, + statuses: Optional[List["_models.InstanceViewStatus"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The virtual machine extension name. + :paramtype name: str + :keyword type: Specifies the type of the extension; an example is "CustomScriptExtension". + :paramtype type: str + :keyword type_handler_version: Specifies the version of the script handler. + :paramtype type_handler_version: str + :keyword substatuses: The resource status information. + :paramtype substatuses: list[~azure.mgmt.computefleet.models.InstanceViewStatus] + :keyword statuses: The resource status information. + :paramtype statuses: list[~azure.mgmt.computefleet.models.InstanceViewStatus] + """ + super().__init__(**kwargs) + self.name = name + self.type = type + self.type_handler_version = type_handler_version + self.substatuses = substatuses + self.statuses = statuses + + +class VirtualMachineScaleSet(_serialization.Model): + """An AzureFleet's virtualMachineScaleSet. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar name: The name of the virtualMachineScaleSet. Required. + :vartype name: str + :ivar id: The compute RP resource id of the virtualMachineScaleSet + "subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmssName}". + Required. + :vartype id: str + :ivar type: Type of the virtualMachineScaleSet. + :vartype type: str + :ivar operation_status: This represents the operationStatus of the VMSS in response to the last + operation that was performed on it by Azure Fleet resource. Required. Known values are: + "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting", and "Migrating". + :vartype operation_status: str or ~azure.mgmt.computefleet.models.ProvisioningState + :ivar error: Error Information when ``operationStatus`` is ``Failed``. + :vartype error: ~azure.mgmt.computefleet.models.ApiError + """ + + _validation = { + "name": {"required": True, "readonly": True}, + "id": {"required": True, "readonly": True}, + "type": {"readonly": True}, + "operation_status": {"required": True, "readonly": True}, + "error": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "operation_status": {"key": "operationStatus", "type": "str"}, + "error": {"key": "error", "type": "ApiError"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.name = None + self.id = None + self.type = None + self.operation_status = None + self.error = None + + +class VirtualMachineScaleSetDataDisk(_serialization.Model): + """Describes a virtual machine scale set data disk. + + All required parameters must be populated in order to send to server. + + :ivar name: The disk name. + :vartype name: str + :ivar lun: Specifies the logical unit number of the data disk. This value is used to identify + data disks within the VM and therefore must be unique for each data disk attached to a VM. + Required. + :vartype lun: int + :ivar caching: Specifies the caching requirements. Possible values are: **None,** **ReadOnly,** + **ReadWrite.** The default values are: **None for Standard storage. ReadOnly for Premium + storage.**. Known values are: "None", "ReadOnly", and "ReadWrite". + :vartype caching: str or ~azure.mgmt.computefleet.models.CachingTypes + :ivar write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or + disabled on the disk. + :vartype write_accelerator_enabled: bool + :ivar create_option: The create option. Required. Known values are: "FromImage", "Empty", and + "Attach". + :vartype create_option: str or ~azure.mgmt.computefleet.models.DiskCreateOptionTypes + :ivar disk_size_gb: Specifies the size of an empty data disk in gigabytes. This element can be + used to overwrite the size of the disk in a virtual machine image. The property diskSizeGB is + the number of bytes x 1024^3 for the disk and the value cannot be larger than 1023. + :vartype disk_size_gb: int + :ivar managed_disk: The managed disk parameters. + :vartype managed_disk: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetManagedDiskParameters + :ivar disk_iops_read_write: Specifies the Read-Write IOPS for the managed disk. Should be used + only when StorageAccountType is UltraSSD_LRS. If not specified, a default value would be + assigned based on diskSizeGB. + :vartype disk_iops_read_write: int + :ivar disk_m_bps_read_write: Specifies the bandwidth in MB per second for the managed disk. + Should be used only when StorageAccountType is UltraSSD_LRS. If not specified, a default value + would be assigned based on diskSizeGB. + :vartype disk_m_bps_read_write: int + :ivar delete_option: Specifies whether data disk should be deleted or detached upon VMSS Flex + deletion (This feature is available for VMSS with Flexible OrchestrationMode + only).:code:`
`:code:`
` Possible values: :code:`
`:code:`
` **Delete** If this + value is used, the data disk is deleted when the VMSS Flex VM is + deleted.:code:`
`:code:`
` **Detach** If this value is used, the data disk is retained + after VMSS Flex VM is deleted.:code:`
`:code:`
` The default value is set to **Delete**. + Known values are: "Delete" and "Detach". + :vartype delete_option: str or ~azure.mgmt.computefleet.models.DiskDeleteOptionTypes + """ + + _validation = { + "lun": {"required": True}, + "create_option": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "lun": {"key": "lun", "type": "int"}, + "caching": {"key": "caching", "type": "str"}, + "write_accelerator_enabled": {"key": "writeAcceleratorEnabled", "type": "bool"}, + "create_option": {"key": "createOption", "type": "str"}, + "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, + "managed_disk": {"key": "managedDisk", "type": "VirtualMachineScaleSetManagedDiskParameters"}, + "disk_iops_read_write": {"key": "diskIOPSReadWrite", "type": "int"}, + "disk_m_bps_read_write": {"key": "diskMBpsReadWrite", "type": "int"}, + "delete_option": {"key": "deleteOption", "type": "str"}, + } + + def __init__( + self, + *, + lun: int, + create_option: Union[str, "_models.DiskCreateOptionTypes"], + name: Optional[str] = None, + caching: Optional[Union[str, "_models.CachingTypes"]] = None, + write_accelerator_enabled: Optional[bool] = None, + disk_size_gb: Optional[int] = None, + managed_disk: Optional["_models.VirtualMachineScaleSetManagedDiskParameters"] = None, + disk_iops_read_write: Optional[int] = None, + disk_m_bps_read_write: Optional[int] = None, + delete_option: Optional[Union[str, "_models.DiskDeleteOptionTypes"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The disk name. + :paramtype name: str + :keyword lun: Specifies the logical unit number of the data disk. This value is used to + identify data disks within the VM and therefore must be unique for each data disk attached to a + VM. Required. + :paramtype lun: int + :keyword caching: Specifies the caching requirements. Possible values are: **None,** + **ReadOnly,** **ReadWrite.** The default values are: **None for Standard storage. ReadOnly for + Premium storage.**. Known values are: "None", "ReadOnly", and "ReadWrite". + :paramtype caching: str or ~azure.mgmt.computefleet.models.CachingTypes + :keyword write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or + disabled on the disk. + :paramtype write_accelerator_enabled: bool + :keyword create_option: The create option. Required. Known values are: "FromImage", "Empty", + and "Attach". + :paramtype create_option: str or ~azure.mgmt.computefleet.models.DiskCreateOptionTypes + :keyword disk_size_gb: Specifies the size of an empty data disk in gigabytes. This element can + be used to overwrite the size of the disk in a virtual machine image. The property diskSizeGB + is the number of bytes x 1024^3 for the disk and the value cannot be larger than 1023. + :paramtype disk_size_gb: int + :keyword managed_disk: The managed disk parameters. + :paramtype managed_disk: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetManagedDiskParameters + :keyword disk_iops_read_write: Specifies the Read-Write IOPS for the managed disk. Should be + used only when StorageAccountType is UltraSSD_LRS. If not specified, a default value would be + assigned based on diskSizeGB. + :paramtype disk_iops_read_write: int + :keyword disk_m_bps_read_write: Specifies the bandwidth in MB per second for the managed disk. + Should be used only when StorageAccountType is UltraSSD_LRS. If not specified, a default value + would be assigned based on diskSizeGB. + :paramtype disk_m_bps_read_write: int + :keyword delete_option: Specifies whether data disk should be deleted or detached upon VMSS + Flex deletion (This feature is available for VMSS with Flexible OrchestrationMode + only).:code:`
`:code:`
` Possible values: :code:`
`:code:`
` **Delete** If this + value is used, the data disk is deleted when the VMSS Flex VM is + deleted.:code:`
`:code:`
` **Detach** If this value is used, the data disk is retained + after VMSS Flex VM is deleted.:code:`
`:code:`
` The default value is set to **Delete**. + Known values are: "Delete" and "Detach". + :paramtype delete_option: str or ~azure.mgmt.computefleet.models.DiskDeleteOptionTypes + """ + super().__init__(**kwargs) + self.name = name + self.lun = lun + self.caching = caching + self.write_accelerator_enabled = write_accelerator_enabled + self.create_option = create_option + self.disk_size_gb = disk_size_gb + self.managed_disk = managed_disk + self.disk_iops_read_write = disk_iops_read_write + self.disk_m_bps_read_write = disk_m_bps_read_write + self.delete_option = delete_option + + +class VirtualMachineScaleSetExtension(SubResourceReadOnly): # pylint: disable=too-many-instance-attributes + """Describes a Virtual Machine Scale Set Extension. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: The name of the extension. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar force_update_tag: If a value is provided and is different from the previous value, the + extension handler will be forced to update even if the extension configuration has not changed. + :vartype force_update_tag: str + :ivar publisher: The name of the extension handler publisher. + :vartype publisher: str + :ivar type_properties_type: Specifies the type of the extension; an example is + "CustomScriptExtension". + :vartype type_properties_type: str + :ivar type_handler_version: Specifies the version of the script handler. + :vartype type_handler_version: str + :ivar auto_upgrade_minor_version: Indicates whether the extension should use a newer minor + version if one is available at deployment time. Once deployed, however, the extension will not + upgrade minor versions unless redeployed, even with this property set to true. + :vartype auto_upgrade_minor_version: bool + :ivar enable_automatic_upgrade: Indicates whether the extension should be automatically + upgraded by the platform if there is a newer version of the extension available. + :vartype enable_automatic_upgrade: bool + :ivar settings: Json formatted public settings for the extension. + :vartype settings: JSON + :ivar protected_settings: The extension can contain either protectedSettings or + protectedSettingsFromKeyVault or no protected settings at all. + :vartype protected_settings: JSON + :ivar provisioning_state: The provisioning state, which only appears in the response. + :vartype provisioning_state: str + :ivar provision_after_extensions: Collection of extension names after which this extension + needs to be provisioned. + :vartype provision_after_extensions: list[str] + :ivar suppress_failures: Indicates whether failures stemming from the extension will be + suppressed (Operational failures such as not connecting to the VM will not be suppressed + regardless of this value). The default is false. + :vartype suppress_failures: bool + :ivar protected_settings_from_key_vault: The extensions protected settings that are passed by + reference, and consumed from key vault. + :vartype protected_settings_from_key_vault: + ~azure.mgmt.computefleet.models.KeyVaultSecretReference + """ + + _validation = { + "id": {"readonly": True}, + "type": {"readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "force_update_tag": {"key": "properties.forceUpdateTag", "type": "str"}, + "publisher": {"key": "properties.publisher", "type": "str"}, + "type_properties_type": {"key": "properties.type", "type": "str"}, + "type_handler_version": {"key": "properties.typeHandlerVersion", "type": "str"}, + "auto_upgrade_minor_version": {"key": "properties.autoUpgradeMinorVersion", "type": "bool"}, + "enable_automatic_upgrade": {"key": "properties.enableAutomaticUpgrade", "type": "bool"}, + "settings": {"key": "properties.settings", "type": "object"}, + "protected_settings": {"key": "properties.protectedSettings", "type": "object"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "provision_after_extensions": {"key": "properties.provisionAfterExtensions", "type": "[str]"}, + "suppress_failures": {"key": "properties.suppressFailures", "type": "bool"}, + "protected_settings_from_key_vault": { + "key": "properties.protectedSettingsFromKeyVault", + "type": "KeyVaultSecretReference", + }, + } + + def __init__( + self, + *, + name: Optional[str] = None, + force_update_tag: Optional[str] = None, + publisher: Optional[str] = None, + type_properties_type: Optional[str] = None, + type_handler_version: Optional[str] = None, + auto_upgrade_minor_version: Optional[bool] = None, + enable_automatic_upgrade: Optional[bool] = None, + settings: Optional[JSON] = None, + protected_settings: Optional[JSON] = None, + provision_after_extensions: Optional[List[str]] = None, + suppress_failures: Optional[bool] = None, + protected_settings_from_key_vault: Optional["_models.KeyVaultSecretReference"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the extension. + :paramtype name: str + :keyword force_update_tag: If a value is provided and is different from the previous value, the + extension handler will be forced to update even if the extension configuration has not changed. + :paramtype force_update_tag: str + :keyword publisher: The name of the extension handler publisher. + :paramtype publisher: str + :keyword type_properties_type: Specifies the type of the extension; an example is + "CustomScriptExtension". + :paramtype type_properties_type: str + :keyword type_handler_version: Specifies the version of the script handler. + :paramtype type_handler_version: str + :keyword auto_upgrade_minor_version: Indicates whether the extension should use a newer minor + version if one is available at deployment time. Once deployed, however, the extension will not + upgrade minor versions unless redeployed, even with this property set to true. + :paramtype auto_upgrade_minor_version: bool + :keyword enable_automatic_upgrade: Indicates whether the extension should be automatically + upgraded by the platform if there is a newer version of the extension available. + :paramtype enable_automatic_upgrade: bool + :keyword settings: Json formatted public settings for the extension. + :paramtype settings: JSON + :keyword protected_settings: The extension can contain either protectedSettings or + protectedSettingsFromKeyVault or no protected settings at all. + :paramtype protected_settings: JSON + :keyword provision_after_extensions: Collection of extension names after which this extension + needs to be provisioned. + :paramtype provision_after_extensions: list[str] + :keyword suppress_failures: Indicates whether failures stemming from the extension will be + suppressed (Operational failures such as not connecting to the VM will not be suppressed + regardless of this value). The default is false. + :paramtype suppress_failures: bool + :keyword protected_settings_from_key_vault: The extensions protected settings that are passed + by reference, and consumed from key vault. + :paramtype protected_settings_from_key_vault: + ~azure.mgmt.computefleet.models.KeyVaultSecretReference + """ + super().__init__(**kwargs) + self.name = name + self.type = None + self.force_update_tag = force_update_tag + self.publisher = publisher + self.type_properties_type = type_properties_type + self.type_handler_version = type_handler_version + self.auto_upgrade_minor_version = auto_upgrade_minor_version + self.enable_automatic_upgrade = enable_automatic_upgrade + self.settings = settings + self.protected_settings = protected_settings + self.provisioning_state = None + self.provision_after_extensions = provision_after_extensions + self.suppress_failures = suppress_failures + self.protected_settings_from_key_vault = protected_settings_from_key_vault + + +class VirtualMachineScaleSetExtensionProfile(_serialization.Model): + """Describes a virtual machine scale set extension profile. + + :ivar extensions: The virtual machine scale set child extension resources. + :vartype extensions: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetExtension] + :ivar extensions_time_budget: Specifies the time alloted for all extensions to start. The time + duration should be between 15 minutes and 120 minutes (inclusive) and should be specified in + ISO 8601 format. The default value is 90 minutes (PT1H30M). Minimum api-version: 2020-06-01. + :vartype extensions_time_budget: str + """ + + _attribute_map = { + "extensions": {"key": "extensions", "type": "[VirtualMachineScaleSetExtension]"}, + "extensions_time_budget": {"key": "extensionsTimeBudget", "type": "str"}, + } + + def __init__( + self, + *, + extensions: Optional[List["_models.VirtualMachineScaleSetExtension"]] = None, + extensions_time_budget: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword extensions: The virtual machine scale set child extension resources. + :paramtype extensions: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetExtension] + :keyword extensions_time_budget: Specifies the time alloted for all extensions to start. The + time duration should be between 15 minutes and 120 minutes (inclusive) and should be specified + in ISO 8601 format. The default value is 90 minutes (PT1H30M). Minimum api-version: 2020-06-01. + :paramtype extensions_time_budget: str + """ + super().__init__(**kwargs) + self.extensions = extensions + self.extensions_time_budget = extensions_time_budget + + +class VirtualMachineScaleSetHardwareProfile(_serialization.Model): + """Specifies the hardware settings for the virtual machine scale set. + + :ivar vm_size_properties: Specifies the properties for customizing the size of the virtual + machine. Minimum api-version: 2021-11-01. Please follow the instructions in `VM Customization + `_ for more details. + :vartype vm_size_properties: ~azure.mgmt.computefleet.models.VMSizeProperties + """ + + _attribute_map = { + "vm_size_properties": {"key": "vmSizeProperties", "type": "VMSizeProperties"}, + } + + def __init__(self, *, vm_size_properties: Optional["_models.VMSizeProperties"] = None, **kwargs: Any) -> None: + """ + :keyword vm_size_properties: Specifies the properties for customizing the size of the virtual + machine. Minimum api-version: 2021-11-01. Please follow the instructions in `VM Customization + `_ for more details. + :paramtype vm_size_properties: ~azure.mgmt.computefleet.models.VMSizeProperties + """ + super().__init__(**kwargs) + self.vm_size_properties = vm_size_properties + + +class VirtualMachineScaleSetIPConfiguration(_serialization.Model): + """Describes a virtual machine scale set network profile's IP configuration. + + All required parameters must be populated in order to send to server. + + :ivar name: The IP configuration name. Required. + :vartype name: str + :ivar subnet: Specifies the identifier of the subnet. + :vartype subnet: ~azure.mgmt.computefleet.models.ApiEntityReference + :ivar primary: Specifies the primary network interface in case the virtual machine has more + than 1 network interface. + :vartype primary: bool + :ivar public_ip_address_configuration: The publicIPAddressConfiguration. + :vartype public_ip_address_configuration: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetPublicIPAddressConfiguration + :ivar private_ip_address_version: Available from Api-Version 2017-03-30 onwards, it represents + whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible + values are: 'IPv4' and 'IPv6'. Known values are: "IPv4" and "IPv6". + :vartype private_ip_address_version: str or ~azure.mgmt.computefleet.models.IPVersion + :ivar application_gateway_backend_address_pools: Specifies an array of references to backend + address pools of application gateways. A scale set can reference backend address pools of + multiple application gateways. Multiple scale sets cannot use the same application gateway. + :vartype application_gateway_backend_address_pools: + list[~azure.mgmt.computefleet.models.SubResource] + :ivar application_security_groups: Specifies an array of references to application security + group. + :vartype application_security_groups: list[~azure.mgmt.computefleet.models.SubResource] + :ivar load_balancer_backend_address_pools: Specifies an array of references to backend address + pools of load balancers. A scale set can reference backend address pools of one public and one + internal load balancer. Multiple scale sets cannot use the same basic sku load balancer. + :vartype load_balancer_backend_address_pools: list[~azure.mgmt.computefleet.models.SubResource] + :ivar load_balancer_inbound_nat_pools: Specifies an array of references to inbound Nat pools of + the load balancers. A scale set can reference inbound nat pools of one public and one internal + load balancer. Multiple scale sets cannot use the same basic sku load balancer. + :vartype load_balancer_inbound_nat_pools: list[~azure.mgmt.computefleet.models.SubResource] + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "subnet": {"key": "properties.subnet", "type": "ApiEntityReference"}, + "primary": {"key": "properties.primary", "type": "bool"}, + "public_ip_address_configuration": { + "key": "properties.publicIPAddressConfiguration", + "type": "VirtualMachineScaleSetPublicIPAddressConfiguration", + }, + "private_ip_address_version": {"key": "properties.privateIPAddressVersion", "type": "str"}, + "application_gateway_backend_address_pools": { + "key": "properties.applicationGatewayBackendAddressPools", + "type": "[SubResource]", + }, + "application_security_groups": {"key": "properties.applicationSecurityGroups", "type": "[SubResource]"}, + "load_balancer_backend_address_pools": { + "key": "properties.loadBalancerBackendAddressPools", + "type": "[SubResource]", + }, + "load_balancer_inbound_nat_pools": {"key": "properties.loadBalancerInboundNatPools", "type": "[SubResource]"}, + } + + def __init__( + self, + *, + name: str, + subnet: Optional["_models.ApiEntityReference"] = None, + primary: Optional[bool] = None, + public_ip_address_configuration: Optional["_models.VirtualMachineScaleSetPublicIPAddressConfiguration"] = None, + private_ip_address_version: Optional[Union[str, "_models.IPVersion"]] = None, + application_gateway_backend_address_pools: Optional[List["_models.SubResource"]] = None, + application_security_groups: Optional[List["_models.SubResource"]] = None, + load_balancer_backend_address_pools: Optional[List["_models.SubResource"]] = None, + load_balancer_inbound_nat_pools: Optional[List["_models.SubResource"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The IP configuration name. Required. + :paramtype name: str + :keyword subnet: Specifies the identifier of the subnet. + :paramtype subnet: ~azure.mgmt.computefleet.models.ApiEntityReference + :keyword primary: Specifies the primary network interface in case the virtual machine has more + than 1 network interface. + :paramtype primary: bool + :keyword public_ip_address_configuration: The publicIPAddressConfiguration. + :paramtype public_ip_address_configuration: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetPublicIPAddressConfiguration + :keyword private_ip_address_version: Available from Api-Version 2017-03-30 onwards, it + represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. + Possible values are: 'IPv4' and 'IPv6'. Known values are: "IPv4" and "IPv6". + :paramtype private_ip_address_version: str or ~azure.mgmt.computefleet.models.IPVersion + :keyword application_gateway_backend_address_pools: Specifies an array of references to backend + address pools of application gateways. A scale set can reference backend address pools of + multiple application gateways. Multiple scale sets cannot use the same application gateway. + :paramtype application_gateway_backend_address_pools: + list[~azure.mgmt.computefleet.models.SubResource] + :keyword application_security_groups: Specifies an array of references to application security + group. + :paramtype application_security_groups: list[~azure.mgmt.computefleet.models.SubResource] + :keyword load_balancer_backend_address_pools: Specifies an array of references to backend + address pools of load balancers. A scale set can reference backend address pools of one public + and one internal load balancer. Multiple scale sets cannot use the same basic sku load + balancer. + :paramtype load_balancer_backend_address_pools: + list[~azure.mgmt.computefleet.models.SubResource] + :keyword load_balancer_inbound_nat_pools: Specifies an array of references to inbound Nat pools + of the load balancers. A scale set can reference inbound nat pools of one public and one + internal load balancer. Multiple scale sets cannot use the same basic sku load balancer. + :paramtype load_balancer_inbound_nat_pools: list[~azure.mgmt.computefleet.models.SubResource] + """ + super().__init__(**kwargs) + self.name = name + self.subnet = subnet + self.primary = primary + self.public_ip_address_configuration = public_ip_address_configuration + self.private_ip_address_version = private_ip_address_version + self.application_gateway_backend_address_pools = application_gateway_backend_address_pools + self.application_security_groups = application_security_groups + self.load_balancer_backend_address_pools = load_balancer_backend_address_pools + self.load_balancer_inbound_nat_pools = load_balancer_inbound_nat_pools + + +class VirtualMachineScaleSetIpTag(_serialization.Model): + """Contains the IP tag associated with the public IP address. + + :ivar ip_tag_type: IP tag type. Example: FirstPartyUsage. + :vartype ip_tag_type: str + :ivar tag: IP tag associated with the public IP. Example: SQL, Storage etc. + :vartype tag: str + """ + + _attribute_map = { + "ip_tag_type": {"key": "ipTagType", "type": "str"}, + "tag": {"key": "tag", "type": "str"}, + } + + def __init__(self, *, ip_tag_type: Optional[str] = None, tag: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword ip_tag_type: IP tag type. Example: FirstPartyUsage. + :paramtype ip_tag_type: str + :keyword tag: IP tag associated with the public IP. Example: SQL, Storage etc. + :paramtype tag: str + """ + super().__init__(**kwargs) + self.ip_tag_type = ip_tag_type + self.tag = tag + + +class VirtualMachineScaleSetListResult(_serialization.Model): + """The response of a VirtualMachineScaleSet list operation. + + All required parameters must be populated in order to send to server. + + :ivar value: The VirtualMachineScaleSet items on this page. Required. + :vartype value: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSet] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[VirtualMachineScaleSet]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: List["_models.VirtualMachineScaleSet"], next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The VirtualMachineScaleSet items on this page. Required. + :paramtype value: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSet] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class VirtualMachineScaleSetManagedDiskParameters(_serialization.Model): # pylint: disable=name-too-long + """Describes the parameters of a ScaleSet managed disk. + + :ivar storage_account_type: Specifies the storage account type for the managed disk. NOTE: + UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk. Known values + are: "Standard_LRS", "Premium_LRS", "StandardSSD_LRS", "UltraSSD_LRS", "Premium_ZRS", + "StandardSSD_ZRS", and "PremiumV2_LRS". + :vartype storage_account_type: str or ~azure.mgmt.computefleet.models.StorageAccountTypes + :ivar disk_encryption_set: Specifies the customer managed disk encryption set resource id for + the managed disk. + :vartype disk_encryption_set: ~azure.mgmt.computefleet.models.DiskEncryptionSetParameters + :ivar security_profile: Specifies the security profile for the managed disk. + :vartype security_profile: ~azure.mgmt.computefleet.models.VMDiskSecurityProfile + """ + + _attribute_map = { + "storage_account_type": {"key": "storageAccountType", "type": "str"}, + "disk_encryption_set": {"key": "diskEncryptionSet", "type": "DiskEncryptionSetParameters"}, + "security_profile": {"key": "securityProfile", "type": "VMDiskSecurityProfile"}, + } + + def __init__( + self, + *, + storage_account_type: Optional[Union[str, "_models.StorageAccountTypes"]] = None, + disk_encryption_set: Optional["_models.DiskEncryptionSetParameters"] = None, + security_profile: Optional["_models.VMDiskSecurityProfile"] = None, + **kwargs: Any + ) -> None: + """ + :keyword storage_account_type: Specifies the storage account type for the managed disk. NOTE: + UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk. Known values + are: "Standard_LRS", "Premium_LRS", "StandardSSD_LRS", "UltraSSD_LRS", "Premium_ZRS", + "StandardSSD_ZRS", and "PremiumV2_LRS". + :paramtype storage_account_type: str or ~azure.mgmt.computefleet.models.StorageAccountTypes + :keyword disk_encryption_set: Specifies the customer managed disk encryption set resource id + for the managed disk. + :paramtype disk_encryption_set: ~azure.mgmt.computefleet.models.DiskEncryptionSetParameters + :keyword security_profile: Specifies the security profile for the managed disk. + :paramtype security_profile: ~azure.mgmt.computefleet.models.VMDiskSecurityProfile + """ + super().__init__(**kwargs) + self.storage_account_type = storage_account_type + self.disk_encryption_set = disk_encryption_set + self.security_profile = security_profile + + +class VirtualMachineScaleSetNetworkConfiguration( + _serialization.Model +): # pylint: disable=too-many-instance-attributes,name-too-long + """Describes a virtual machine scale set network profile's network configurations. + + All required parameters must be populated in order to send to server. + + :ivar name: The network configuration name. Required. + :vartype name: str + :ivar primary: Specifies the primary network interface in case the virtual machine has more + than 1 network interface. + :vartype primary: bool + :ivar enable_accelerated_networking: Specifies whether the network interface is accelerated + networking-enabled. + :vartype enable_accelerated_networking: bool + :ivar disable_tcp_state_tracking: Specifies whether the network interface is disabled for tcp + state tracking. + :vartype disable_tcp_state_tracking: bool + :ivar enable_fpga: Specifies whether the network interface is FPGA networking-enabled. + :vartype enable_fpga: bool + :ivar network_security_group: The network security group. + :vartype network_security_group: ~azure.mgmt.computefleet.models.SubResource + :ivar dns_settings: The dns settings to be applied on the network interfaces. + :vartype dns_settings: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetNetworkConfigurationDnsSettings + :ivar ip_configurations: Specifies the IP configurations of the network interface. + :vartype ip_configurations: + list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetIPConfiguration] + :ivar enable_ip_forwarding: Whether IP forwarding enabled on this NIC. + :vartype enable_ip_forwarding: bool + :ivar delete_option: Specify what happens to the network interface when the VM is deleted. + Known values are: "Delete" and "Detach". + :vartype delete_option: str or ~azure.mgmt.computefleet.models.DeleteOptions + :ivar auxiliary_mode: Specifies whether the Auxiliary mode is enabled for the Network Interface + resource. Known values are: "None", "AcceleratedConnections", and "Floating". + :vartype auxiliary_mode: str or ~azure.mgmt.computefleet.models.NetworkInterfaceAuxiliaryMode + :ivar auxiliary_sku: Specifies whether the Auxiliary sku is enabled for the Network Interface + resource. Known values are: "None", "A1", "A2", "A4", and "A8". + :vartype auxiliary_sku: str or ~azure.mgmt.computefleet.models.NetworkInterfaceAuxiliarySku + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "primary": {"key": "properties.primary", "type": "bool"}, + "enable_accelerated_networking": {"key": "properties.enableAcceleratedNetworking", "type": "bool"}, + "disable_tcp_state_tracking": {"key": "properties.disableTcpStateTracking", "type": "bool"}, + "enable_fpga": {"key": "properties.enableFpga", "type": "bool"}, + "network_security_group": {"key": "properties.networkSecurityGroup", "type": "SubResource"}, + "dns_settings": { + "key": "properties.dnsSettings", + "type": "VirtualMachineScaleSetNetworkConfigurationDnsSettings", + }, + "ip_configurations": {"key": "properties.ipConfigurations", "type": "[VirtualMachineScaleSetIPConfiguration]"}, + "enable_ip_forwarding": {"key": "properties.enableIPForwarding", "type": "bool"}, + "delete_option": {"key": "properties.deleteOption", "type": "str"}, + "auxiliary_mode": {"key": "properties.auxiliaryMode", "type": "str"}, + "auxiliary_sku": {"key": "properties.auxiliarySku", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + primary: Optional[bool] = None, + enable_accelerated_networking: Optional[bool] = None, + disable_tcp_state_tracking: Optional[bool] = None, + enable_fpga: Optional[bool] = None, + network_security_group: Optional["_models.SubResource"] = None, + dns_settings: Optional["_models.VirtualMachineScaleSetNetworkConfigurationDnsSettings"] = None, + ip_configurations: Optional[List["_models.VirtualMachineScaleSetIPConfiguration"]] = None, + enable_ip_forwarding: Optional[bool] = None, + delete_option: Optional[Union[str, "_models.DeleteOptions"]] = None, + auxiliary_mode: Optional[Union[str, "_models.NetworkInterfaceAuxiliaryMode"]] = None, + auxiliary_sku: Optional[Union[str, "_models.NetworkInterfaceAuxiliarySku"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The network configuration name. Required. + :paramtype name: str + :keyword primary: Specifies the primary network interface in case the virtual machine has more + than 1 network interface. + :paramtype primary: bool + :keyword enable_accelerated_networking: Specifies whether the network interface is accelerated + networking-enabled. + :paramtype enable_accelerated_networking: bool + :keyword disable_tcp_state_tracking: Specifies whether the network interface is disabled for + tcp state tracking. + :paramtype disable_tcp_state_tracking: bool + :keyword enable_fpga: Specifies whether the network interface is FPGA networking-enabled. + :paramtype enable_fpga: bool + :keyword network_security_group: The network security group. + :paramtype network_security_group: ~azure.mgmt.computefleet.models.SubResource + :keyword dns_settings: The dns settings to be applied on the network interfaces. + :paramtype dns_settings: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetNetworkConfigurationDnsSettings + :keyword ip_configurations: Specifies the IP configurations of the network interface. + :paramtype ip_configurations: + list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetIPConfiguration] + :keyword enable_ip_forwarding: Whether IP forwarding enabled on this NIC. + :paramtype enable_ip_forwarding: bool + :keyword delete_option: Specify what happens to the network interface when the VM is deleted. + Known values are: "Delete" and "Detach". + :paramtype delete_option: str or ~azure.mgmt.computefleet.models.DeleteOptions + :keyword auxiliary_mode: Specifies whether the Auxiliary mode is enabled for the Network + Interface resource. Known values are: "None", "AcceleratedConnections", and "Floating". + :paramtype auxiliary_mode: str or ~azure.mgmt.computefleet.models.NetworkInterfaceAuxiliaryMode + :keyword auxiliary_sku: Specifies whether the Auxiliary sku is enabled for the Network + Interface resource. Known values are: "None", "A1", "A2", "A4", and "A8". + :paramtype auxiliary_sku: str or ~azure.mgmt.computefleet.models.NetworkInterfaceAuxiliarySku + """ + super().__init__(**kwargs) + self.name = name + self.primary = primary + self.enable_accelerated_networking = enable_accelerated_networking + self.disable_tcp_state_tracking = disable_tcp_state_tracking + self.enable_fpga = enable_fpga + self.network_security_group = network_security_group + self.dns_settings = dns_settings + self.ip_configurations = ip_configurations + self.enable_ip_forwarding = enable_ip_forwarding + self.delete_option = delete_option + self.auxiliary_mode = auxiliary_mode + self.auxiliary_sku = auxiliary_sku + + +class VirtualMachineScaleSetNetworkConfigurationDnsSettings(_serialization.Model): # pylint: disable=name-too-long + """Describes a virtual machines scale sets network configuration's DNS settings. + + :ivar dns_servers: List of DNS servers IP addresses. + :vartype dns_servers: list[str] + """ + + _attribute_map = { + "dns_servers": {"key": "dnsServers", "type": "[str]"}, + } + + def __init__(self, *, dns_servers: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword dns_servers: List of DNS servers IP addresses. + :paramtype dns_servers: list[str] + """ + super().__init__(**kwargs) + self.dns_servers = dns_servers + + +class VirtualMachineScaleSetNetworkProfile(_serialization.Model): + """Describes a virtual machine scale set network profile. + + :ivar health_probe: A reference to a load balancer probe used to determine the health of an + instance in the virtual machine scale set. The reference will be in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. # pylint: disable=line-too-long + :vartype health_probe: ~azure.mgmt.computefleet.models.ApiEntityReference + :ivar network_interface_configurations: The list of network configurations. + :vartype network_interface_configurations: + list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetNetworkConfiguration] + :ivar network_api_version: specifies the Microsoft.Network API version used when creating + networking resources in the Network Interface Configurations for Virtual Machine Scale Set with + orchestration mode 'Flexible'. "2020-11-01" + :vartype network_api_version: str or ~azure.mgmt.computefleet.models.NetworkApiVersion + """ + + _attribute_map = { + "health_probe": {"key": "healthProbe", "type": "ApiEntityReference"}, + "network_interface_configurations": { + "key": "networkInterfaceConfigurations", + "type": "[VirtualMachineScaleSetNetworkConfiguration]", + }, + "network_api_version": {"key": "networkApiVersion", "type": "str"}, + } + + def __init__( + self, + *, + health_probe: Optional["_models.ApiEntityReference"] = None, + network_interface_configurations: Optional[List["_models.VirtualMachineScaleSetNetworkConfiguration"]] = None, + network_api_version: Optional[Union[str, "_models.NetworkApiVersion"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword health_probe: A reference to a load balancer probe used to determine the health of an + instance in the virtual machine scale set. The reference will be in the form: + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. # pylint: disable=line-too-long + :paramtype health_probe: ~azure.mgmt.computefleet.models.ApiEntityReference + :keyword network_interface_configurations: The list of network configurations. + :paramtype network_interface_configurations: + list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetNetworkConfiguration] + :keyword network_api_version: specifies the Microsoft.Network API version used when creating + networking resources in the Network Interface Configurations for Virtual Machine Scale Set with + orchestration mode 'Flexible'. "2020-11-01" + :paramtype network_api_version: str or ~azure.mgmt.computefleet.models.NetworkApiVersion + """ + super().__init__(**kwargs) + self.health_probe = health_probe + self.network_interface_configurations = network_interface_configurations + self.network_api_version = network_api_version + + +class VirtualMachineScaleSetOSDisk(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Describes a virtual machine scale set operating system disk. + + All required parameters must be populated in order to send to server. + + :ivar name: The disk name. + :vartype name: str + :ivar caching: Specifies the caching requirements. Possible values are: **None,** **ReadOnly,** + **ReadWrite.** The default values are: **None for Standard storage. ReadOnly for Premium + storage.**. Known values are: "None", "ReadOnly", and "ReadWrite". + :vartype caching: str or ~azure.mgmt.computefleet.models.CachingTypes + :ivar write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or + disabled on the disk. + :vartype write_accelerator_enabled: bool + :ivar create_option: Specifies how the virtual machines in the scale set should be created. The + only allowed value is: **FromImage.** This value is used when you are using an image to create + the virtual machine. If you are using a platform image, you also use the imageReference element + described above. If you are using a marketplace image, you also use the plan element + previously described. Required. Known values are: "FromImage", "Empty", and "Attach". + :vartype create_option: str or ~azure.mgmt.computefleet.models.DiskCreateOptionTypes + :ivar diff_disk_settings: Specifies the ephemeral disk Settings for the operating system disk + used by the virtual machine scale set. + :vartype diff_disk_settings: ~azure.mgmt.computefleet.models.DiffDiskSettings + :ivar disk_size_gb: Specifies the size of an empty data disk in gigabytes. This element can be + used to overwrite the size of the disk in a virtual machine image. The property 'diskSizeGB' is + the number of bytes x 1024^3 for the disk and the value cannot be larger than 1023. + :vartype disk_size_gb: int + :ivar os_type: This property allows you to specify the type of the OS that is included in the + disk if creating a VM from user-image or a specialized VHD. Possible values are: **Windows,** + **Linux.**. Known values are: "Windows" and "Linux". + :vartype os_type: str or ~azure.mgmt.computefleet.models.OperatingSystemTypes + :ivar image: Specifies information about the unmanaged user image to base the scale set on. + :vartype image: ~azure.mgmt.computefleet.models.VirtualHardDisk + :ivar vhd_containers: Specifies the container urls that are used to store operating system + disks for the scale set. + :vartype vhd_containers: list[str] + :ivar managed_disk: The managed disk parameters. + :vartype managed_disk: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetManagedDiskParameters + :ivar delete_option: Specifies whether OS Disk should be deleted or detached upon VMSS Flex + deletion (This feature is available for VMSS with Flexible OrchestrationMode only). + :code:`
`:code:`
` Possible values: :code:`
`:code:`
` **Delete** If this value is + used, the OS disk is deleted when VMSS Flex VM is deleted.:code:`
`:code:`
` **Detach** + If this value is used, the OS disk is retained after VMSS Flex VM is deleted. + :code:`
`:code:`
` The default value is set to **Delete**. For an Ephemeral OS Disk, the + default value is set to **Delete**. User cannot change the delete option for Ephemeral OS Disk. + Known values are: "Delete" and "Detach". + :vartype delete_option: str or ~azure.mgmt.computefleet.models.DiskDeleteOptionTypes + """ + + _validation = { + "create_option": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "caching": {"key": "caching", "type": "str"}, + "write_accelerator_enabled": {"key": "writeAcceleratorEnabled", "type": "bool"}, + "create_option": {"key": "createOption", "type": "str"}, + "diff_disk_settings": {"key": "diffDiskSettings", "type": "DiffDiskSettings"}, + "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, + "os_type": {"key": "osType", "type": "str"}, + "image": {"key": "image", "type": "VirtualHardDisk"}, + "vhd_containers": {"key": "vhdContainers", "type": "[str]"}, + "managed_disk": {"key": "managedDisk", "type": "VirtualMachineScaleSetManagedDiskParameters"}, + "delete_option": {"key": "deleteOption", "type": "str"}, + } + + def __init__( + self, + *, + create_option: Union[str, "_models.DiskCreateOptionTypes"], + name: Optional[str] = None, + caching: Optional[Union[str, "_models.CachingTypes"]] = None, + write_accelerator_enabled: Optional[bool] = None, + diff_disk_settings: Optional["_models.DiffDiskSettings"] = None, + disk_size_gb: Optional[int] = None, + os_type: Optional[Union[str, "_models.OperatingSystemTypes"]] = None, + image: Optional["_models.VirtualHardDisk"] = None, + vhd_containers: Optional[List[str]] = None, + managed_disk: Optional["_models.VirtualMachineScaleSetManagedDiskParameters"] = None, + delete_option: Optional[Union[str, "_models.DiskDeleteOptionTypes"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The disk name. + :paramtype name: str + :keyword caching: Specifies the caching requirements. Possible values are: **None,** + **ReadOnly,** **ReadWrite.** The default values are: **None for Standard storage. ReadOnly for + Premium storage.**. Known values are: "None", "ReadOnly", and "ReadWrite". + :paramtype caching: str or ~azure.mgmt.computefleet.models.CachingTypes + :keyword write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or + disabled on the disk. + :paramtype write_accelerator_enabled: bool + :keyword create_option: Specifies how the virtual machines in the scale set should be created. + The only allowed value is: **FromImage.** This value is used when you are using an image to + create the virtual machine. If you are using a platform image, you also use the imageReference + element described above. If you are using a marketplace image, you also use the plan element + previously described. Required. Known values are: "FromImage", "Empty", and "Attach". + :paramtype create_option: str or ~azure.mgmt.computefleet.models.DiskCreateOptionTypes + :keyword diff_disk_settings: Specifies the ephemeral disk Settings for the operating system + disk used by the virtual machine scale set. + :paramtype diff_disk_settings: ~azure.mgmt.computefleet.models.DiffDiskSettings + :keyword disk_size_gb: Specifies the size of an empty data disk in gigabytes. This element can + be used to overwrite the size of the disk in a virtual machine image. The property 'diskSizeGB' + is the number of bytes x 1024^3 for the disk and the value cannot be larger than 1023. + :paramtype disk_size_gb: int + :keyword os_type: This property allows you to specify the type of the OS that is included in + the disk if creating a VM from user-image or a specialized VHD. Possible values are: + **Windows,** **Linux.**. Known values are: "Windows" and "Linux". + :paramtype os_type: str or ~azure.mgmt.computefleet.models.OperatingSystemTypes + :keyword image: Specifies information about the unmanaged user image to base the scale set on. + :paramtype image: ~azure.mgmt.computefleet.models.VirtualHardDisk + :keyword vhd_containers: Specifies the container urls that are used to store operating system + disks for the scale set. + :paramtype vhd_containers: list[str] + :keyword managed_disk: The managed disk parameters. + :paramtype managed_disk: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetManagedDiskParameters + :keyword delete_option: Specifies whether OS Disk should be deleted or detached upon VMSS Flex + deletion (This feature is available for VMSS with Flexible OrchestrationMode only). + :code:`
`:code:`
` Possible values: :code:`
`:code:`
` **Delete** If this value is + used, the OS disk is deleted when VMSS Flex VM is deleted.:code:`
`:code:`
` **Detach** + If this value is used, the OS disk is retained after VMSS Flex VM is deleted. + :code:`
`:code:`
` The default value is set to **Delete**. For an Ephemeral OS Disk, the + default value is set to **Delete**. User cannot change the delete option for Ephemeral OS Disk. + Known values are: "Delete" and "Detach". + :paramtype delete_option: str or ~azure.mgmt.computefleet.models.DiskDeleteOptionTypes + """ + super().__init__(**kwargs) + self.name = name + self.caching = caching + self.write_accelerator_enabled = write_accelerator_enabled + self.create_option = create_option + self.diff_disk_settings = diff_disk_settings + self.disk_size_gb = disk_size_gb + self.os_type = os_type + self.image = image + self.vhd_containers = vhd_containers + self.managed_disk = managed_disk + self.delete_option = delete_option + + +class VirtualMachineScaleSetOSProfile(_serialization.Model): + """Describes a virtual machine scale set OS profile. + + :ivar computer_name_prefix: Specifies the computer name prefix for all of the virtual machines + in the scale set. Computer name prefixes must be 1 to 15 characters long. + :vartype computer_name_prefix: str + :ivar admin_username: Specifies the name of the administrator account. :code:`
`:code:`
` + **Windows-only restriction:** Cannot end in "." :code:`
`:code:`
` **Disallowed values:** + "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", + "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", + "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", + "test3", "user4", "user5". :code:`
`:code:`
` **Minimum-length (Linux):** 1 character + :code:`
`:code:`
` **Max-length (Linux):** 64 characters :code:`
`:code:`
` + **Max-length (Windows):** 20 characters. + :vartype admin_username: str + :ivar admin_password: Specifies the password of the administrator account. + :code:`
`:code:`
` **Minimum-length (Windows):** 8 characters :code:`
`:code:`
` + **Minimum-length (Linux):** 6 characters :code:`
`:code:`
` **Max-length (Windows):** 123 + characters :code:`
`:code:`
` **Max-length (Linux):** 72 characters + :code:`
`:code:`
` **Complexity requirements:** 3 out of 4 conditions below need to be + fulfilled :code:`
` Has lower characters :code:`
`Has upper characters :code:`
` Has a + digit :code:`
` Has a special character (Regex match [\\W_]) :code:`
`:code:`
` + **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", + "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" :code:`
`:code:`
` For + resetting the password, see `How to reset the Remote Desktop service or its login password in a + Windows VM `_ + :code:`
`:code:`
` For resetting root password, see `Manage users, SSH, and check or + repair disks on Azure Linux VMs using the VMAccess Extension + `_. + :vartype admin_password: str + :ivar custom_data: Specifies a base-64 encoded string of custom data. The base-64 encoded + string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum + length of the binary array is 65535 bytes. For using cloud-init for your VM, see `Using + cloud-init to customize a Linux VM during creation + `_. + :vartype custom_data: str + :ivar windows_configuration: Specifies Windows operating system settings on the virtual + machine. + :vartype windows_configuration: ~azure.mgmt.computefleet.models.WindowsConfiguration + :ivar linux_configuration: Specifies the Linux operating system settings on the virtual + machine. For a list of supported Linux distributions, see `Linux on Azure-Endorsed + Distributions `_. + :vartype linux_configuration: ~azure.mgmt.computefleet.models.LinuxConfiguration + :ivar secrets: Specifies set of certificates that should be installed onto the virtual machines + in the scale set. To install certificates on a virtual machine it is recommended to use the + `Azure Key Vault virtual machine extension for Linux + `_ or the `Azure + Key Vault virtual machine extension for Windows + `_. + :vartype secrets: list[~azure.mgmt.computefleet.models.VaultSecretGroup] + :ivar allow_extension_operations: Specifies whether extension operations should be allowed on + the virtual machine scale set. This may only be set to False when no extensions are present on + the virtual machine scale set. + :vartype allow_extension_operations: bool + :ivar require_guest_provision_signal: Optional property which must either be set to True or + omitted. + :vartype require_guest_provision_signal: bool + """ + + _attribute_map = { + "computer_name_prefix": {"key": "computerNamePrefix", "type": "str"}, + "admin_username": {"key": "adminUsername", "type": "str"}, + "admin_password": {"key": "adminPassword", "type": "str"}, + "custom_data": {"key": "customData", "type": "str"}, + "windows_configuration": {"key": "windowsConfiguration", "type": "WindowsConfiguration"}, + "linux_configuration": {"key": "linuxConfiguration", "type": "LinuxConfiguration"}, + "secrets": {"key": "secrets", "type": "[VaultSecretGroup]"}, + "allow_extension_operations": {"key": "allowExtensionOperations", "type": "bool"}, + "require_guest_provision_signal": {"key": "requireGuestProvisionSignal", "type": "bool"}, + } + + def __init__( + self, + *, + computer_name_prefix: Optional[str] = None, + admin_username: Optional[str] = None, + admin_password: Optional[str] = None, + custom_data: Optional[str] = None, + windows_configuration: Optional["_models.WindowsConfiguration"] = None, + linux_configuration: Optional["_models.LinuxConfiguration"] = None, + secrets: Optional[List["_models.VaultSecretGroup"]] = None, + allow_extension_operations: Optional[bool] = None, + require_guest_provision_signal: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword computer_name_prefix: Specifies the computer name prefix for all of the virtual + machines in the scale set. Computer name prefixes must be 1 to 15 characters long. + :paramtype computer_name_prefix: str + :keyword admin_username: Specifies the name of the administrator account. + :code:`
`:code:`
` **Windows-only restriction:** Cannot end in "." + :code:`
`:code:`
` **Disallowed values:** "administrator", "admin", "user", "user1", + "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", + "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", + "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". + :code:`
`:code:`
` **Minimum-length (Linux):** 1 character :code:`
`:code:`
` + **Max-length (Linux):** 64 characters :code:`
`:code:`
` **Max-length (Windows):** 20 + characters. + :paramtype admin_username: str + :keyword admin_password: Specifies the password of the administrator account. + :code:`
`:code:`
` **Minimum-length (Windows):** 8 characters :code:`
`:code:`
` + **Minimum-length (Linux):** 6 characters :code:`
`:code:`
` **Max-length (Windows):** 123 + characters :code:`
`:code:`
` **Max-length (Linux):** 72 characters + :code:`
`:code:`
` **Complexity requirements:** 3 out of 4 conditions below need to be + fulfilled :code:`
` Has lower characters :code:`
`Has upper characters :code:`
` Has a + digit :code:`
` Has a special character (Regex match [\\W_]) :code:`
`:code:`
` + **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", + "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" :code:`
`:code:`
` For + resetting the password, see `How to reset the Remote Desktop service or its login password in a + Windows VM `_ + :code:`
`:code:`
` For resetting root password, see `Manage users, SSH, and check or + repair disks on Azure Linux VMs using the VMAccess Extension + `_. + :paramtype admin_password: str + :keyword custom_data: Specifies a base-64 encoded string of custom data. The base-64 encoded + string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum + length of the binary array is 65535 bytes. For using cloud-init for your VM, see `Using + cloud-init to customize a Linux VM during creation + `_. + :paramtype custom_data: str + :keyword windows_configuration: Specifies Windows operating system settings on the virtual + machine. + :paramtype windows_configuration: ~azure.mgmt.computefleet.models.WindowsConfiguration + :keyword linux_configuration: Specifies the Linux operating system settings on the virtual + machine. For a list of supported Linux distributions, see `Linux on Azure-Endorsed + Distributions `_. + :paramtype linux_configuration: ~azure.mgmt.computefleet.models.LinuxConfiguration + :keyword secrets: Specifies set of certificates that should be installed onto the virtual + machines in the scale set. To install certificates on a virtual machine it is recommended to + use the `Azure Key Vault virtual machine extension for Linux + `_ or the `Azure + Key Vault virtual machine extension for Windows + `_. + :paramtype secrets: list[~azure.mgmt.computefleet.models.VaultSecretGroup] + :keyword allow_extension_operations: Specifies whether extension operations should be allowed + on the virtual machine scale set. This may only be set to False when no extensions are present + on the virtual machine scale set. + :paramtype allow_extension_operations: bool + :keyword require_guest_provision_signal: Optional property which must either be set to True or + omitted. + :paramtype require_guest_provision_signal: bool + """ + super().__init__(**kwargs) + self.computer_name_prefix = computer_name_prefix + self.admin_username = admin_username + self.admin_password = admin_password + self.custom_data = custom_data + self.windows_configuration = windows_configuration + self.linux_configuration = linux_configuration + self.secrets = secrets + self.allow_extension_operations = allow_extension_operations + self.require_guest_provision_signal = require_guest_provision_signal + + +class VirtualMachineScaleSetPublicIPAddressConfiguration(_serialization.Model): # pylint: disable=name-too-long + """Describes a virtual machines scale set IP Configuration's PublicIPAddress configuration. + + All required parameters must be populated in order to send to server. + + :ivar name: The publicIP address configuration name. Required. + :vartype name: str + :ivar sku: Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible. + :vartype sku: ~azure.mgmt.computefleet.models.PublicIPAddressSku + :ivar idle_timeout_in_minutes: The idle timeout of the public IP address. + :vartype idle_timeout_in_minutes: int + :ivar dns_settings: The dns settings to be applied on the publicIP addresses . + :vartype dns_settings: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings + :ivar ip_tags: The list of IP tags associated with the public IP address. + :vartype ip_tags: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetIpTag] + :ivar public_ip_prefix: The PublicIPPrefix from which to allocate publicIP addresses. + :vartype public_ip_prefix: ~azure.mgmt.computefleet.models.SubResource + :ivar public_ip_address_version: Available from Api-Version 2019-07-01 onwards, it represents + whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values + are: 'IPv4' and 'IPv6'. Known values are: "IPv4" and "IPv6". + :vartype public_ip_address_version: str or ~azure.mgmt.computefleet.models.IPVersion + :ivar delete_option: Specify what happens to the public IP when the VM is deleted. Known values + are: "Delete" and "Detach". + :vartype delete_option: str or ~azure.mgmt.computefleet.models.DeleteOptions + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "sku": {"key": "sku", "type": "PublicIPAddressSku"}, + "idle_timeout_in_minutes": {"key": "properties.idleTimeoutInMinutes", "type": "int"}, + "dns_settings": { + "key": "properties.dnsSettings", + "type": "VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings", + }, + "ip_tags": {"key": "properties.ipTags", "type": "[VirtualMachineScaleSetIpTag]"}, + "public_ip_prefix": {"key": "properties.publicIPPrefix", "type": "SubResource"}, + "public_ip_address_version": {"key": "properties.publicIPAddressVersion", "type": "str"}, + "delete_option": {"key": "properties.deleteOption", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + sku: Optional["_models.PublicIPAddressSku"] = None, + idle_timeout_in_minutes: Optional[int] = None, + dns_settings: Optional["_models.VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings"] = None, + ip_tags: Optional[List["_models.VirtualMachineScaleSetIpTag"]] = None, + public_ip_prefix: Optional["_models.SubResource"] = None, + public_ip_address_version: Optional[Union[str, "_models.IPVersion"]] = None, + delete_option: Optional[Union[str, "_models.DeleteOptions"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: The publicIP address configuration name. Required. + :paramtype name: str + :keyword sku: Describes the public IP Sku. It can only be set with OrchestrationMode as + Flexible. + :paramtype sku: ~azure.mgmt.computefleet.models.PublicIPAddressSku + :keyword idle_timeout_in_minutes: The idle timeout of the public IP address. + :paramtype idle_timeout_in_minutes: int + :keyword dns_settings: The dns settings to be applied on the publicIP addresses . + :paramtype dns_settings: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings + :keyword ip_tags: The list of IP tags associated with the public IP address. + :paramtype ip_tags: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetIpTag] + :keyword public_ip_prefix: The PublicIPPrefix from which to allocate publicIP addresses. + :paramtype public_ip_prefix: ~azure.mgmt.computefleet.models.SubResource + :keyword public_ip_address_version: Available from Api-Version 2019-07-01 onwards, it + represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. + Possible values are: 'IPv4' and 'IPv6'. Known values are: "IPv4" and "IPv6". + :paramtype public_ip_address_version: str or ~azure.mgmt.computefleet.models.IPVersion + :keyword delete_option: Specify what happens to the public IP when the VM is deleted. Known + values are: "Delete" and "Detach". + :paramtype delete_option: str or ~azure.mgmt.computefleet.models.DeleteOptions + """ + super().__init__(**kwargs) + self.name = name + self.sku = sku + self.idle_timeout_in_minutes = idle_timeout_in_minutes + self.dns_settings = dns_settings + self.ip_tags = ip_tags + self.public_ip_prefix = public_ip_prefix + self.public_ip_address_version = public_ip_address_version + self.delete_option = delete_option + + +class VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings( + _serialization.Model +): # pylint: disable=name-too-long + """Describes a virtual machines scale sets network configuration's DNS settings. + + All required parameters must be populated in order to send to server. + + :ivar domain_name_label: The Domain name label.The concatenation of the domain name label and + vm index will be the domain name labels of the PublicIPAddress resources that will be created. + Required. + :vartype domain_name_label: str + :ivar domain_name_label_scope: The Domain name label scope.The concatenation of the hashed + domain name label that generated according to the policy from domain name label scope and vm + index will be the domain name labels of the PublicIPAddress resources that will be created. + Known values are: "TenantReuse", "SubscriptionReuse", "ResourceGroupReuse", and "NoReuse". + :vartype domain_name_label_scope: str or + ~azure.mgmt.computefleet.models.DomainNameLabelScopeTypes + """ + + _validation = { + "domain_name_label": {"required": True}, + } + + _attribute_map = { + "domain_name_label": {"key": "domainNameLabel", "type": "str"}, + "domain_name_label_scope": {"key": "domainNameLabelScope", "type": "str"}, + } + + def __init__( + self, + *, + domain_name_label: str, + domain_name_label_scope: Optional[Union[str, "_models.DomainNameLabelScopeTypes"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword domain_name_label: The Domain name label.The concatenation of the domain name label + and vm index will be the domain name labels of the PublicIPAddress resources that will be + created. Required. + :paramtype domain_name_label: str + :keyword domain_name_label_scope: The Domain name label scope.The concatenation of the hashed + domain name label that generated according to the policy from domain name label scope and vm + index will be the domain name labels of the PublicIPAddress resources that will be created. + Known values are: "TenantReuse", "SubscriptionReuse", "ResourceGroupReuse", and "NoReuse". + :paramtype domain_name_label_scope: str or + ~azure.mgmt.computefleet.models.DomainNameLabelScopeTypes + """ + super().__init__(**kwargs) + self.domain_name_label = domain_name_label + self.domain_name_label_scope = domain_name_label_scope + + +class VirtualMachineScaleSetStorageProfile(_serialization.Model): + """Describes a virtual machine scale set storage profile. + + :ivar image_reference: Specifies information about the image to use. You can specify + information about platform images, marketplace images, or virtual machine images. This element + is required when you want to use a platform image, marketplace image, or virtual machine image, + but is not used in other creation operations. + :vartype image_reference: ~azure.mgmt.computefleet.models.ImageReference + :ivar os_disk: Specifies information about the operating system disk used by the virtual + machines in the scale set. For more information about disks, see `About disks and VHDs for + Azure virtual machines + `_. + :vartype os_disk: ~azure.mgmt.computefleet.models.VirtualMachineScaleSetOSDisk + :ivar data_disks: Specifies the parameters that are used to add data disks to the virtual + machines in the scale set. For more information about disks, see `About disks and VHDs for + Azure virtual machines + `_. + :vartype data_disks: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetDataDisk] + :ivar disk_controller_type: + :vartype disk_controller_type: str + """ + + _attribute_map = { + "image_reference": {"key": "imageReference", "type": "ImageReference"}, + "os_disk": {"key": "osDisk", "type": "VirtualMachineScaleSetOSDisk"}, + "data_disks": {"key": "dataDisks", "type": "[VirtualMachineScaleSetDataDisk]"}, + "disk_controller_type": {"key": "diskControllerType", "type": "str"}, + } + + def __init__( + self, + *, + image_reference: Optional["_models.ImageReference"] = None, + os_disk: Optional["_models.VirtualMachineScaleSetOSDisk"] = None, + data_disks: Optional[List["_models.VirtualMachineScaleSetDataDisk"]] = None, + disk_controller_type: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword image_reference: Specifies information about the image to use. You can specify + information about platform images, marketplace images, or virtual machine images. This element + is required when you want to use a platform image, marketplace image, or virtual machine image, + but is not used in other creation operations. + :paramtype image_reference: ~azure.mgmt.computefleet.models.ImageReference + :keyword os_disk: Specifies information about the operating system disk used by the virtual + machines in the scale set. For more information about disks, see `About disks and VHDs for + Azure virtual machines + `_. + :paramtype os_disk: ~azure.mgmt.computefleet.models.VirtualMachineScaleSetOSDisk + :keyword data_disks: Specifies the parameters that are used to add data disks to the virtual + machines in the scale set. For more information about disks, see `About disks and VHDs for + Azure virtual machines + `_. + :paramtype data_disks: list[~azure.mgmt.computefleet.models.VirtualMachineScaleSetDataDisk] + :keyword disk_controller_type: + :paramtype disk_controller_type: str + """ + super().__init__(**kwargs) + self.image_reference = image_reference + self.os_disk = os_disk + self.data_disks = data_disks + self.disk_controller_type = disk_controller_type + + +class VirtualMachineScaleSetVMProfile(_serialization.Model): # pylint: disable=too-many-instance-attributes + """Describes a virtual machine scale set virtual machine profile. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar os_profile: Specifies the operating system settings for the virtual machines in the scale + set. + :vartype os_profile: ~azure.mgmt.computefleet.models.VirtualMachineScaleSetOSProfile + :ivar storage_profile: Specifies the storage settings for the virtual machine disks. + :vartype storage_profile: ~azure.mgmt.computefleet.models.VirtualMachineScaleSetStorageProfile + :ivar network_profile: Specifies properties of the network interfaces of the virtual machines + in the scale set. + :vartype network_profile: ~azure.mgmt.computefleet.models.VirtualMachineScaleSetNetworkProfile + :ivar security_profile: Specifies the Security related profile settings for the virtual + machines in the scale set. + :vartype security_profile: ~azure.mgmt.computefleet.models.SecurityProfile + :ivar diagnostics_profile: Specifies the boot diagnostic settings state. Minimum api-version: + 2015-06-15. + :vartype diagnostics_profile: ~azure.mgmt.computefleet.models.DiagnosticsProfile + :ivar extension_profile: Specifies a collection of settings for extensions installed on virtual + machines in the scale set. + :vartype extension_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetExtensionProfile + :ivar license_type: Specifies that the image or disk that is being used was licensed + on-premises. :code:`
`:code:`
` Possible values for Windows Server operating system are: + :code:`
`:code:`
` Windows_Client :code:`
`:code:`
` Windows_Server + :code:`
`:code:`
` Possible values for Linux Server operating system are: + :code:`
`:code:`
` RHEL_BYOS (for RHEL) :code:`
`:code:`
` SLES_BYOS (for SUSE) + :code:`
`:code:`
` For more information, see `Azure Hybrid Use Benefit for Windows Server + `_ + :code:`
`:code:`
` `Azure Hybrid Use Benefit for Linux Server + `_ + :code:`
`:code:`
` Minimum api-version: 2015-06-15. + :vartype license_type: str + :ivar priority: Specifies the priority for the virtual machines in the scale set. Minimum + api-version: 2017-10-30-preview. Known values are: "Regular", "Low", and "Spot". + :vartype priority: str or ~azure.mgmt.computefleet.models.VirtualMachinePriorityTypes + :ivar eviction_policy: Specifies the eviction policy for the Azure Spot virtual machine and + Azure Spot scale set. For Azure Spot virtual machines, both 'Deallocate' and 'Delete' are + supported and the minimum api-version is 2019-03-01. For Azure Spot scale sets, both + 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview. + Known values are: "Deallocate" and "Delete". + :vartype eviction_policy: str or + ~azure.mgmt.computefleet.models.VirtualMachineEvictionPolicyTypes + :ivar billing_profile: Specifies the billing related details of a Azure Spot VMSS. Minimum + api-version: 2019-03-01. + :vartype billing_profile: ~azure.mgmt.computefleet.models.BillingProfile + :ivar scheduled_events_profile: Specifies Scheduled Event related configurations. + :vartype scheduled_events_profile: ~azure.mgmt.computefleet.models.ScheduledEventsProfile + :ivar user_data: UserData for the virtual machines in the scale set, which must be base-64 + encoded. Customer should not pass any secrets in here. Minimum api-version: 2021-03-01. + :vartype user_data: str + :ivar capacity_reservation: Specifies the capacity reservation related details of a scale set. + Minimum api-version: 2021-04-01. + :vartype capacity_reservation: ~azure.mgmt.computefleet.models.CapacityReservationProfile + :ivar application_profile: Specifies the gallery applications that should be made available to + the VM/VMSS. + :vartype application_profile: ~azure.mgmt.computefleet.models.ApplicationProfile + :ivar hardware_profile: Specifies the hardware profile related details of a scale set. Minimum + api-version: 2021-11-01. + :vartype hardware_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetHardwareProfile + :ivar service_artifact_reference: Specifies the service artifact reference id used to set same + image version for all virtual machines in the scale set when using 'latest' image version. + Minimum api-version: 2022-11-01. + :vartype service_artifact_reference: ~azure.mgmt.computefleet.models.ServiceArtifactReference + :ivar security_posture_reference: Specifies the security posture to be used for all virtual + machines in the scale set. Minimum api-version: 2023-03-01. + :vartype security_posture_reference: ~azure.mgmt.computefleet.models.SecurityPostureReference + :ivar time_created: Specifies the time in which this VM profile for the Virtual Machine Scale + Set was created. Minimum API version for this property is 2023-09-01. This value will be added + to VMSS Flex VM tags when creating/updating the VMSS VM Profile with minimum api-version + 2023-09-01. + :vartype time_created: ~datetime.datetime + """ + + _validation = { + "time_created": {"readonly": True}, + } + + _attribute_map = { + "os_profile": {"key": "osProfile", "type": "VirtualMachineScaleSetOSProfile"}, + "storage_profile": {"key": "storageProfile", "type": "VirtualMachineScaleSetStorageProfile"}, + "network_profile": {"key": "networkProfile", "type": "VirtualMachineScaleSetNetworkProfile"}, + "security_profile": {"key": "securityProfile", "type": "SecurityProfile"}, + "diagnostics_profile": {"key": "diagnosticsProfile", "type": "DiagnosticsProfile"}, + "extension_profile": {"key": "extensionProfile", "type": "VirtualMachineScaleSetExtensionProfile"}, + "license_type": {"key": "licenseType", "type": "str"}, + "priority": {"key": "priority", "type": "str"}, + "eviction_policy": {"key": "evictionPolicy", "type": "str"}, + "billing_profile": {"key": "billingProfile", "type": "BillingProfile"}, + "scheduled_events_profile": {"key": "scheduledEventsProfile", "type": "ScheduledEventsProfile"}, + "user_data": {"key": "userData", "type": "str"}, + "capacity_reservation": {"key": "capacityReservation", "type": "CapacityReservationProfile"}, + "application_profile": {"key": "applicationProfile", "type": "ApplicationProfile"}, + "hardware_profile": {"key": "hardwareProfile", "type": "VirtualMachineScaleSetHardwareProfile"}, + "service_artifact_reference": {"key": "serviceArtifactReference", "type": "ServiceArtifactReference"}, + "security_posture_reference": {"key": "securityPostureReference", "type": "SecurityPostureReference"}, + "time_created": {"key": "timeCreated", "type": "iso-8601"}, + } + + def __init__( + self, + *, + os_profile: Optional["_models.VirtualMachineScaleSetOSProfile"] = None, + storage_profile: Optional["_models.VirtualMachineScaleSetStorageProfile"] = None, + network_profile: Optional["_models.VirtualMachineScaleSetNetworkProfile"] = None, + security_profile: Optional["_models.SecurityProfile"] = None, + diagnostics_profile: Optional["_models.DiagnosticsProfile"] = None, + extension_profile: Optional["_models.VirtualMachineScaleSetExtensionProfile"] = None, + license_type: Optional[str] = None, + priority: Optional[Union[str, "_models.VirtualMachinePriorityTypes"]] = None, + eviction_policy: Optional[Union[str, "_models.VirtualMachineEvictionPolicyTypes"]] = None, + billing_profile: Optional["_models.BillingProfile"] = None, + scheduled_events_profile: Optional["_models.ScheduledEventsProfile"] = None, + user_data: Optional[str] = None, + capacity_reservation: Optional["_models.CapacityReservationProfile"] = None, + application_profile: Optional["_models.ApplicationProfile"] = None, + hardware_profile: Optional["_models.VirtualMachineScaleSetHardwareProfile"] = None, + service_artifact_reference: Optional["_models.ServiceArtifactReference"] = None, + security_posture_reference: Optional["_models.SecurityPostureReference"] = None, + **kwargs: Any + ) -> None: + """ + :keyword os_profile: Specifies the operating system settings for the virtual machines in the + scale set. + :paramtype os_profile: ~azure.mgmt.computefleet.models.VirtualMachineScaleSetOSProfile + :keyword storage_profile: Specifies the storage settings for the virtual machine disks. + :paramtype storage_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetStorageProfile + :keyword network_profile: Specifies properties of the network interfaces of the virtual + machines in the scale set. + :paramtype network_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetNetworkProfile + :keyword security_profile: Specifies the Security related profile settings for the virtual + machines in the scale set. + :paramtype security_profile: ~azure.mgmt.computefleet.models.SecurityProfile + :keyword diagnostics_profile: Specifies the boot diagnostic settings state. Minimum + api-version: 2015-06-15. + :paramtype diagnostics_profile: ~azure.mgmt.computefleet.models.DiagnosticsProfile + :keyword extension_profile: Specifies a collection of settings for extensions installed on + virtual machines in the scale set. + :paramtype extension_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetExtensionProfile + :keyword license_type: Specifies that the image or disk that is being used was licensed + on-premises. :code:`
`:code:`
` Possible values for Windows Server operating system are: + :code:`
`:code:`
` Windows_Client :code:`
`:code:`
` Windows_Server + :code:`
`:code:`
` Possible values for Linux Server operating system are: + :code:`
`:code:`
` RHEL_BYOS (for RHEL) :code:`
`:code:`
` SLES_BYOS (for SUSE) + :code:`
`:code:`
` For more information, see `Azure Hybrid Use Benefit for Windows Server + `_ + :code:`
`:code:`
` `Azure Hybrid Use Benefit for Linux Server + `_ + :code:`
`:code:`
` Minimum api-version: 2015-06-15. + :paramtype license_type: str + :keyword priority: Specifies the priority for the virtual machines in the scale set. Minimum + api-version: 2017-10-30-preview. Known values are: "Regular", "Low", and "Spot". + :paramtype priority: str or ~azure.mgmt.computefleet.models.VirtualMachinePriorityTypes + :keyword eviction_policy: Specifies the eviction policy for the Azure Spot virtual machine and + Azure Spot scale set. For Azure Spot virtual machines, both 'Deallocate' and 'Delete' are + supported and the minimum api-version is 2019-03-01. For Azure Spot scale sets, both + 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview. + Known values are: "Deallocate" and "Delete". + :paramtype eviction_policy: str or + ~azure.mgmt.computefleet.models.VirtualMachineEvictionPolicyTypes + :keyword billing_profile: Specifies the billing related details of a Azure Spot VMSS. Minimum + api-version: 2019-03-01. + :paramtype billing_profile: ~azure.mgmt.computefleet.models.BillingProfile + :keyword scheduled_events_profile: Specifies Scheduled Event related configurations. + :paramtype scheduled_events_profile: ~azure.mgmt.computefleet.models.ScheduledEventsProfile + :keyword user_data: UserData for the virtual machines in the scale set, which must be base-64 + encoded. Customer should not pass any secrets in here. Minimum api-version: 2021-03-01. + :paramtype user_data: str + :keyword capacity_reservation: Specifies the capacity reservation related details of a scale + set. Minimum api-version: 2021-04-01. + :paramtype capacity_reservation: ~azure.mgmt.computefleet.models.CapacityReservationProfile + :keyword application_profile: Specifies the gallery applications that should be made available + to the VM/VMSS. + :paramtype application_profile: ~azure.mgmt.computefleet.models.ApplicationProfile + :keyword hardware_profile: Specifies the hardware profile related details of a scale set. + Minimum api-version: 2021-11-01. + :paramtype hardware_profile: + ~azure.mgmt.computefleet.models.VirtualMachineScaleSetHardwareProfile + :keyword service_artifact_reference: Specifies the service artifact reference id used to set + same image version for all virtual machines in the scale set when using 'latest' image version. + Minimum api-version: 2022-11-01. + :paramtype service_artifact_reference: ~azure.mgmt.computefleet.models.ServiceArtifactReference + :keyword security_posture_reference: Specifies the security posture to be used for all virtual + machines in the scale set. Minimum api-version: 2023-03-01. + :paramtype security_posture_reference: ~azure.mgmt.computefleet.models.SecurityPostureReference + """ + super().__init__(**kwargs) + self.os_profile = os_profile + self.storage_profile = storage_profile + self.network_profile = network_profile + self.security_profile = security_profile + self.diagnostics_profile = diagnostics_profile + self.extension_profile = extension_profile + self.license_type = license_type + self.priority = priority + self.eviction_policy = eviction_policy + self.billing_profile = billing_profile + self.scheduled_events_profile = scheduled_events_profile + self.user_data = user_data + self.capacity_reservation = capacity_reservation + self.application_profile = application_profile + self.hardware_profile = hardware_profile + self.service_artifact_reference = service_artifact_reference + self.security_posture_reference = security_posture_reference + self.time_created = None + + +class VMDiskSecurityProfile(_serialization.Model): + """Specifies the security profile settings for the managed disk. **Note:** It can only be set for + Confidential VMs. + + :ivar security_encryption_type: Specifies the EncryptionType of the managed disk. It is set to + DiskWithVMGuestState for encryption of the managed disk along with VMGuestState blob, + VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not + persisting firmware state in the VMGuestState blob.. **Note:** It can be set for only + Confidential VMs. Known values are: "VMGuestStateOnly", "DiskWithVMGuestState", and + "NonPersistedTPM". + :vartype security_encryption_type: str or + ~azure.mgmt.computefleet.models.SecurityEncryptionTypes + :ivar disk_encryption_set: Specifies the customer managed disk encryption set resource id for + the managed disk that is used for Customer Managed Key encrypted ConfidentialVM OS Disk and + VMGuest blob. + :vartype disk_encryption_set: ~azure.mgmt.computefleet.models.DiskEncryptionSetParameters + """ + + _attribute_map = { + "security_encryption_type": {"key": "securityEncryptionType", "type": "str"}, + "disk_encryption_set": {"key": "diskEncryptionSet", "type": "DiskEncryptionSetParameters"}, + } + + def __init__( + self, + *, + security_encryption_type: Optional[Union[str, "_models.SecurityEncryptionTypes"]] = None, + disk_encryption_set: Optional["_models.DiskEncryptionSetParameters"] = None, + **kwargs: Any + ) -> None: + """ + :keyword security_encryption_type: Specifies the EncryptionType of the managed disk. It is set + to DiskWithVMGuestState for encryption of the managed disk along with VMGuestState blob, + VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not + persisting firmware state in the VMGuestState blob.. **Note:** It can be set for only + Confidential VMs. Known values are: "VMGuestStateOnly", "DiskWithVMGuestState", and + "NonPersistedTPM". + :paramtype security_encryption_type: str or + ~azure.mgmt.computefleet.models.SecurityEncryptionTypes + :keyword disk_encryption_set: Specifies the customer managed disk encryption set resource id + for the managed disk that is used for Customer Managed Key encrypted ConfidentialVM OS Disk and + VMGuest blob. + :paramtype disk_encryption_set: ~azure.mgmt.computefleet.models.DiskEncryptionSetParameters + """ + super().__init__(**kwargs) + self.security_encryption_type = security_encryption_type + self.disk_encryption_set = disk_encryption_set + + +class VMGalleryApplication(_serialization.Model): + """Specifies the required information to reference a compute gallery application version. + + All required parameters must be populated in order to send to server. + + :ivar tags: Optional, Specifies a passthrough value for more generic context. + :vartype tags: str + :ivar order: Optional, Specifies the order in which the packages have to be installed. + :vartype order: int + :ivar package_reference_id: Specifies the GalleryApplicationVersion resource id on the form of + /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{application}/versions/{version}. # pylint: disable=line-too-long + Required. + :vartype package_reference_id: str + :ivar configuration_reference: Optional, Specifies the uri to an azure blob that will replace + the default configuration for the package if provided. + :vartype configuration_reference: str + :ivar treat_failure_as_deployment_failure: Optional, If true, any failure for any operation in + the VmApplication will fail the deployment. + :vartype treat_failure_as_deployment_failure: bool + :ivar enable_automatic_upgrade: If set to true, when a new Gallery Application version is + available in PIR/SIG, it will be automatically updated for the VM/VMSS. + :vartype enable_automatic_upgrade: bool + """ + + _validation = { + "package_reference_id": {"required": True}, + } + + _attribute_map = { + "tags": {"key": "tags", "type": "str"}, + "order": {"key": "order", "type": "int"}, + "package_reference_id": {"key": "packageReferenceId", "type": "str"}, + "configuration_reference": {"key": "configurationReference", "type": "str"}, + "treat_failure_as_deployment_failure": {"key": "treatFailureAsDeploymentFailure", "type": "bool"}, + "enable_automatic_upgrade": {"key": "enableAutomaticUpgrade", "type": "bool"}, + } + + def __init__( + self, + *, + package_reference_id: str, + tags: Optional[str] = None, + order: Optional[int] = None, + configuration_reference: Optional[str] = None, + treat_failure_as_deployment_failure: Optional[bool] = None, + enable_automatic_upgrade: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Optional, Specifies a passthrough value for more generic context. + :paramtype tags: str + :keyword order: Optional, Specifies the order in which the packages have to be installed. + :paramtype order: int + :keyword package_reference_id: Specifies the GalleryApplicationVersion resource id on the form + of + /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{application}/versions/{version}. # pylint: disable=line-too-long + Required. + :paramtype package_reference_id: str + :keyword configuration_reference: Optional, Specifies the uri to an azure blob that will + replace the default configuration for the package if provided. + :paramtype configuration_reference: str + :keyword treat_failure_as_deployment_failure: Optional, If true, any failure for any operation + in the VmApplication will fail the deployment. + :paramtype treat_failure_as_deployment_failure: bool + :keyword enable_automatic_upgrade: If set to true, when a new Gallery Application version is + available in PIR/SIG, it will be automatically updated for the VM/VMSS. + :paramtype enable_automatic_upgrade: bool + """ + super().__init__(**kwargs) + self.tags = tags + self.order = order + self.package_reference_id = package_reference_id + self.configuration_reference = configuration_reference + self.treat_failure_as_deployment_failure = treat_failure_as_deployment_failure + self.enable_automatic_upgrade = enable_automatic_upgrade + + +class VmSizeProfile(_serialization.Model): + """Specifications about a VM Size. This will also contain the corresponding rank and weight in + future. + + All required parameters must be populated in order to send to server. + + :ivar name: The Sku name (e.g. 'Standard_DS1_v2'). Required. + :vartype name: str + :ivar rank: The rank of the VM size. This is used with + 'RegularPriorityAllocationStrategy.Prioritized' + The lower the number, the higher the priority. Starting with 0. + :vartype rank: int + """ + + _validation = { + "name": {"required": True}, + "rank": {"maximum": 65535, "minimum": 0}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "rank": {"key": "rank", "type": "int"}, + } + + def __init__(self, *, name: str, rank: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword name: The Sku name (e.g. 'Standard_DS1_v2'). Required. + :paramtype name: str + :keyword rank: The rank of the VM size. This is used with + 'RegularPriorityAllocationStrategy.Prioritized' + The lower the number, the higher the priority. Starting with 0. + :paramtype rank: int + """ + super().__init__(**kwargs) + self.name = name + self.rank = rank + + +class VMSizeProperties(_serialization.Model): + """Specifies VM Size Property settings on the virtual machine. + + :ivar v_cpus_available: Specifies the number of vCPUs available for the VM. When this property + is not specified in the request body the default behavior is to set it to the value of vCPUs + available for that VM size exposed in api response of `List all available virtual machine sizes + in a region `_. + :vartype v_cpus_available: int + :ivar v_cpus_per_core: Specifies the vCPU to physical core ratio. When this property is not + specified in the request body the default behavior is set to the value of vCPUsPerCore for the + VM Size exposed in api response of `List all available virtual machine sizes in a region + `_. **Setting this + property to 1 also means that hyper-threading is disabled.**. + :vartype v_cpus_per_core: int + """ + + _attribute_map = { + "v_cpus_available": {"key": "vCPUsAvailable", "type": "int"}, + "v_cpus_per_core": {"key": "vCPUsPerCore", "type": "int"}, + } + + def __init__( + self, *, v_cpus_available: Optional[int] = None, v_cpus_per_core: Optional[int] = None, **kwargs: Any + ) -> None: + """ + :keyword v_cpus_available: Specifies the number of vCPUs available for the VM. When this + property is not specified in the request body the default behavior is to set it to the value of + vCPUs available for that VM size exposed in api response of `List all available virtual machine + sizes in a region `_. + :paramtype v_cpus_available: int + :keyword v_cpus_per_core: Specifies the vCPU to physical core ratio. When this property is not + specified in the request body the default behavior is set to the value of vCPUsPerCore for the + VM Size exposed in api response of `List all available virtual machine sizes in a region + `_. **Setting this + property to 1 also means that hyper-threading is disabled.**. + :paramtype v_cpus_per_core: int + """ + super().__init__(**kwargs) + self.v_cpus_available = v_cpus_available + self.v_cpus_per_core = v_cpus_per_core + + +class WindowsConfiguration(_serialization.Model): + """Specifies Windows operating system settings on the virtual machine. + + :ivar provision_vm_agent: Indicates whether virtual machine agent should be provisioned on the + virtual machine. When this property is not specified in the request body, it is set to true by + default. This will ensure that VM Agent is installed on the VM so that extensions can be added + to the VM later. + :vartype provision_vm_agent: bool + :ivar enable_automatic_updates: Indicates whether Automatic Updates is enabled for the Windows + virtual machine. Default value is true. For virtual machine scale sets, this property can be + updated and updates will take effect on OS reprovisioning. + :vartype enable_automatic_updates: bool + :ivar time_zone: Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time". + Possible values can be `TimeZoneInfo.Id + `_ value + from time zones returned by `TimeZoneInfo.GetSystemTimeZones + `_. + :vartype time_zone: str + :ivar additional_unattend_content: Specifies additional base-64 encoded XML formatted + information that can be included in the Unattend.xml file, which is used by Windows Setup. + :vartype additional_unattend_content: + list[~azure.mgmt.computefleet.models.AdditionalUnattendContent] + :ivar patch_settings: [Preview Feature] Specifies settings related to VM Guest Patching on + Windows. + :vartype patch_settings: ~azure.mgmt.computefleet.models.PatchSettings + :ivar win_rm: Specifies the Windows Remote Management listeners. This enables remote Windows + PowerShell. + :vartype win_rm: ~azure.mgmt.computefleet.models.WinRMConfiguration + :ivar enable_vm_agent_platform_updates: Indicates whether VMAgent Platform Updates is enabled + for the Windows virtual machine. Default value is false. + :vartype enable_vm_agent_platform_updates: bool + """ + + _attribute_map = { + "provision_vm_agent": {"key": "provisionVMAgent", "type": "bool"}, + "enable_automatic_updates": {"key": "enableAutomaticUpdates", "type": "bool"}, + "time_zone": {"key": "timeZone", "type": "str"}, + "additional_unattend_content": {"key": "additionalUnattendContent", "type": "[AdditionalUnattendContent]"}, + "patch_settings": {"key": "patchSettings", "type": "PatchSettings"}, + "win_rm": {"key": "winRM", "type": "WinRMConfiguration"}, + "enable_vm_agent_platform_updates": {"key": "enableVMAgentPlatformUpdates", "type": "bool"}, + } + + def __init__( + self, + *, + provision_vm_agent: Optional[bool] = None, + enable_automatic_updates: Optional[bool] = None, + time_zone: Optional[str] = None, + additional_unattend_content: Optional[List["_models.AdditionalUnattendContent"]] = None, + patch_settings: Optional["_models.PatchSettings"] = None, + win_rm: Optional["_models.WinRMConfiguration"] = None, + enable_vm_agent_platform_updates: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword provision_vm_agent: Indicates whether virtual machine agent should be provisioned on + the virtual machine. When this property is not specified in the request body, it is set to true + by default. This will ensure that VM Agent is installed on the VM so that extensions can be + added to the VM later. + :paramtype provision_vm_agent: bool + :keyword enable_automatic_updates: Indicates whether Automatic Updates is enabled for the + Windows virtual machine. Default value is true. For virtual machine scale sets, this property + can be updated and updates will take effect on OS reprovisioning. + :paramtype enable_automatic_updates: bool + :keyword time_zone: Specifies the time zone of the virtual machine. e.g. "Pacific Standard + Time". Possible values can be `TimeZoneInfo.Id + `_ value + from time zones returned by `TimeZoneInfo.GetSystemTimeZones + `_. + :paramtype time_zone: str + :keyword additional_unattend_content: Specifies additional base-64 encoded XML formatted + information that can be included in the Unattend.xml file, which is used by Windows Setup. + :paramtype additional_unattend_content: + list[~azure.mgmt.computefleet.models.AdditionalUnattendContent] + :keyword patch_settings: [Preview Feature] Specifies settings related to VM Guest Patching on + Windows. + :paramtype patch_settings: ~azure.mgmt.computefleet.models.PatchSettings + :keyword win_rm: Specifies the Windows Remote Management listeners. This enables remote Windows + PowerShell. + :paramtype win_rm: ~azure.mgmt.computefleet.models.WinRMConfiguration + :keyword enable_vm_agent_platform_updates: Indicates whether VMAgent Platform Updates is + enabled for the Windows virtual machine. Default value is false. + :paramtype enable_vm_agent_platform_updates: bool + """ + super().__init__(**kwargs) + self.provision_vm_agent = provision_vm_agent + self.enable_automatic_updates = enable_automatic_updates + self.time_zone = time_zone + self.additional_unattend_content = additional_unattend_content + self.patch_settings = patch_settings + self.win_rm = win_rm + self.enable_vm_agent_platform_updates = enable_vm_agent_platform_updates + + +class WindowsVMGuestPatchAutomaticByPlatformSettings(_serialization.Model): # pylint: disable=name-too-long + """Specifies additional settings to be applied when patch mode AutomaticByPlatform is selected in + Windows patch settings. + + :ivar reboot_setting: Specifies the reboot setting for all AutomaticByPlatform patch + installation operations. Known values are: "Unknown", "IfRequired", "Never", and "Always". + :vartype reboot_setting: str or + ~azure.mgmt.computefleet.models.WindowsVMGuestPatchAutomaticByPlatformRebootSetting + :ivar bypass_platform_safety_checks_on_user_schedule: Enables customer to schedule patching + without accidental upgrades. + :vartype bypass_platform_safety_checks_on_user_schedule: bool + """ + + _attribute_map = { + "reboot_setting": {"key": "rebootSetting", "type": "str"}, + "bypass_platform_safety_checks_on_user_schedule": { + "key": "bypassPlatformSafetyChecksOnUserSchedule", + "type": "bool", + }, + } + + def __init__( + self, + *, + reboot_setting: Optional[Union[str, "_models.WindowsVMGuestPatchAutomaticByPlatformRebootSetting"]] = None, + bypass_platform_safety_checks_on_user_schedule: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword reboot_setting: Specifies the reboot setting for all AutomaticByPlatform patch + installation operations. Known values are: "Unknown", "IfRequired", "Never", and "Always". + :paramtype reboot_setting: str or + ~azure.mgmt.computefleet.models.WindowsVMGuestPatchAutomaticByPlatformRebootSetting + :keyword bypass_platform_safety_checks_on_user_schedule: Enables customer to schedule patching + without accidental upgrades. + :paramtype bypass_platform_safety_checks_on_user_schedule: bool + """ + super().__init__(**kwargs) + self.reboot_setting = reboot_setting + self.bypass_platform_safety_checks_on_user_schedule = bypass_platform_safety_checks_on_user_schedule + + +class WinRMConfiguration(_serialization.Model): + """Describes Windows Remote Management configuration of the VM. + + :ivar listeners: The list of Windows Remote Management listeners. + :vartype listeners: list[~azure.mgmt.computefleet.models.WinRMListener] + """ + + _attribute_map = { + "listeners": {"key": "listeners", "type": "[WinRMListener]"}, + } + + def __init__(self, *, listeners: Optional[List["_models.WinRMListener"]] = None, **kwargs: Any) -> None: + """ + :keyword listeners: The list of Windows Remote Management listeners. + :paramtype listeners: list[~azure.mgmt.computefleet.models.WinRMListener] + """ + super().__init__(**kwargs) + self.listeners = listeners + + +class WinRMListener(_serialization.Model): + """Describes Protocol and thumbprint of Windows Remote Management listener. + + :ivar protocol: Specifies the protocol of WinRM listener. Possible values are: **http,** + **https.**. Known values are: "Http" and "Https". + :vartype protocol: str or ~azure.mgmt.computefleet.models.ProtocolTypes + :ivar certificate_url: This is the URL of a certificate that has been uploaded to Key Vault as + a secret. For adding a secret to the Key Vault, see `Add a key or secret to the key vault + `_. In this case, your + certificate needs to be the Base64 encoding of the following JSON Object which is encoded in + UTF-8: :code:`
`:code:`
` {:code:`
` + "data":":code:``",:code:`
` "dataType":"pfx",:code:`
` + "password":":code:``":code:`
`} :code:`
` To install certificates on a + virtual machine it is recommended to use the `Azure Key Vault virtual machine extension for + Linux `_ or the + `Azure Key Vault virtual machine extension for Windows + `_. + :vartype certificate_url: str + """ + + _attribute_map = { + "protocol": {"key": "protocol", "type": "str"}, + "certificate_url": {"key": "certificateUrl", "type": "str"}, + } + + def __init__( + self, + *, + protocol: Optional[Union[str, "_models.ProtocolTypes"]] = None, + certificate_url: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword protocol: Specifies the protocol of WinRM listener. Possible values are: **http,** + **https.**. Known values are: "Http" and "Https". + :paramtype protocol: str or ~azure.mgmt.computefleet.models.ProtocolTypes + :keyword certificate_url: This is the URL of a certificate that has been uploaded to Key Vault + as a secret. For adding a secret to the Key Vault, see `Add a key or secret to the key vault + `_. In this case, your + certificate needs to be the Base64 encoding of the following JSON Object which is encoded in + UTF-8: :code:`
`:code:`
` {:code:`
` + "data":":code:``",:code:`
` "dataType":"pfx",:code:`
` + "password":":code:``":code:`
`} :code:`
` To install certificates on a + virtual machine it is recommended to use the `Azure Key Vault virtual machine extension for + Linux `_ or the + `Azure Key Vault virtual machine extension for Windows + `_. + :paramtype certificate_url: str + """ + super().__init__(**kwargs) + self.protocol = protocol + self.certificate_url = certificate_url diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_patch.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/__init__.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/__init__.py new file mode 100644 index 000000000000..11d54761c024 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/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 Operations +from ._fleets_operations import FleetsOperations +from ._virtual_machine_scale_sets_operations import VirtualMachineScaleSetsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "FleetsOperations", + "VirtualMachineScaleSetsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_fleets_operations.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_fleets_operations.py new file mode 100644 index 000000000000..a6b3db4fcd1d --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_fleets_operations.py @@ -0,0 +1,947 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AzureFleet/fleets") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # 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_get_request(resource_group_name: str, fleet_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "fleetName": _SERIALIZER.url("fleet_name", fleet_name, "str", pattern=r"^[^_\W][\w-._]{0,79}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "fleetName": _SERIALIZER.url("fleet_name", fleet_name, "str", pattern=r"^[^_\W][\w-._]{0,79}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "fleetName": _SERIALIZER.url("fleet_name", fleet_name, "str", pattern=r"^[^_\W][\w-._]{0,79}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "fleetName": _SERIALIZER.url("fleet_name", fleet_name, "str", pattern=r"^[^_\W][\w-._]{0,79}(? Iterable["_models.Fleet"]: + """List Fleet resources by subscription ID. + + :return: An iterator like instance of either Fleet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FleetListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FleetListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Fleet"]: + """List Fleet resources by resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either Fleet or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FleetListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FleetListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, resource_group_name: str, fleet_name: str, **kwargs: Any) -> _models.Fleet: + """Get a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :return: Fleet or the result of cls(response) + :rtype: ~azure.mgmt.computefleet.models.Fleet + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("Fleet", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, resource_group_name: str, fleet_name: str, resource: Union[_models.Fleet, IO[bytes]], **kwargs: Any + ) -> _models.Fleet: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "Fleet") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("Fleet", pipeline_response) + + if response.status_code == 201: + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = self._deserialize("Fleet", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + fleet_name: str, + resource: _models.Fleet, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Fleet]: + """Create a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.computefleet.models.Fleet + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + fleet_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Fleet]: + """Create a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, resource_group_name: str, fleet_name: str, resource: Union[_models.Fleet, IO[bytes]], **kwargs: Any + ) -> LROPoller[_models.Fleet]: + """Create a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param resource: Resource create parameters. Is either a Fleet type or a IO[bytes] type. + Required. + :type resource: ~azure.mgmt.computefleet.models.Fleet or IO[bytes] + :return: An instance of LROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Fleet", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.Fleet].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.Fleet]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + resource_group_name: str, + fleet_name: str, + properties: Union[_models.FleetUpdate, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.Fleet]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.Fleet]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "FleetUpdate") + + _request = build_update_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("Fleet", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + fleet_name: str, + properties: _models.FleetUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Fleet]: + """Update a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.computefleet.models.FleetUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + fleet_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Fleet]: + """Update a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + fleet_name: str, + properties: Union[_models.FleetUpdate, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.Fleet]: + """Update a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :param properties: The resource properties to be updated. Is either a FleetUpdate type or a + IO[bytes] type. Required. + :type properties: ~azure.mgmt.computefleet.models.FleetUpdate or IO[bytes] + :return: An instance of LROPoller that returns either Fleet or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.computefleet.models.Fleet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Fleet] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + properties=properties, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("Fleet", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.Fleet].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.Fleet]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, fleet_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + fleet_name=fleet_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, fleet_name: str, **kwargs: Any) -> LROPoller[None]: + """Delete a Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param fleet_name: The name of the Compute Fleet. Required. + :type fleet_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + fleet_name=fleet_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_operations.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_operations.py new file mode 100644 index 000000000000..d657ddcc4604 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_operations.py @@ -0,0 +1,156 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.AzureFleet/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.computefleet.MicrosoftAzureFleet`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.computefleet.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_patch.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/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/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_virtual_machine_scale_sets_operations.py b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_virtual_machine_scale_sets_operations.py new file mode 100644 index 000000000000..3179563e024a --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/operations/_virtual_machine_scale_sets_operations.py @@ -0,0 +1,181 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_fleet_request( + resource_group_name: str, name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{name}/virtualMachineScaleSets", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "name": _SERIALIZER.url("name", name, "str", pattern=r"^[^_\W][\w-._]{0,79}(? Iterable["_models.VirtualMachineScaleSet"]: + """List VirtualMachineScaleSet resources by Fleet. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the Fleet. Required. + :type name: str + :return: An iterator like instance of either VirtualMachineScaleSet or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.computefleet.models.VirtualMachineScaleSet] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.VirtualMachineScaleSetListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_fleet_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("VirtualMachineScaleSetListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/py.typed b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/azure/mgmt/computefleet/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_create_or_update.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_create_or_update.py new file mode 100644 index 000000000000..817459dcaa2c --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_create_or_update.py @@ -0,0 +1,340 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python fleets_create_or_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="1DC2F28C-A625-4B0E-9748-9885A3C9E9EB", + ) + + response = client.fleets.begin_create_or_update( + resource_group_name="rgazurefleet", + fleet_name="testFleet", + resource={ + "identity": {"type": "UserAssigned", "userAssignedIdentities": {"key9851": {}}}, + "location": "westus", + "properties": { + "computeProfile": { + "baseVirtualMachineProfile": { + "applicationProfile": { + "galleryApplications": [ + { + "configurationReference": "ulztmiavpojpbpbddgnuuiimxcpau", + "enableAutomaticUpgrade": True, + "order": 5, + "packageReferenceId": "lfxqiadouhmbovcd", + "tags": "eyrqjbib", + "treatFailureAsDeploymentFailure": True, + } + ] + }, + "billingProfile": {"maxPrice": 2}, + "capacityReservation": {"capacityReservationGroup": {"id": "groxwd"}}, + "diagnosticsProfile": {"bootDiagnostics": {"enabled": True, "storageUri": "rzamfwghybpx"}}, + "evictionPolicy": "Deallocate", + "extensionProfile": { + "extensions": [ + { + "name": "bndxuxx", + "properties": { + "autoUpgradeMinorVersion": True, + "enableAutomaticUpgrade": True, + "forceUpdateTag": "yhgxw", + "protectedSettings": {}, + "protectedSettingsFromKeyVault": { + "secretUrl": "vyhzfkqsqanacgzjthpjoe", + "sourceVault": {"id": "groxwd"}, + }, + "provisionAfterExtensions": ["nftzosroolbcwmpupujzqwqe"], + "publisher": "kpxtirxjfprhs", + "settings": {}, + "suppressFailures": True, + "type": "pgjilctjjwaa", + "typeHandlerVersion": "zevivcoilxmbwlrihhhibq", + }, + } + ], + "extensionsTimeBudget": "mbhjahtdygwgyszdwjtvlvtgchdwil", + }, + "hardwareProfile": {"vmSizeProperties": {"vCPUsAvailable": 16, "vCPUsPerCore": 23}}, + "licenseType": "v", + "networkProfile": { + "healthProbe": {"id": "cmkfcjhmrwxwqtac"}, + "networkApiVersion": "2020-11-01", + "networkInterfaceConfigurations": [ + { + "name": "i", + "properties": { + "auxiliaryMode": "None", + "auxiliarySku": "None", + "deleteOption": "Delete", + "disableTcpStateTracking": True, + "dnsSettings": {"dnsServers": ["nxmmfolhclsesu"]}, + "enableAcceleratedNetworking": True, + "enableFpga": True, + "enableIPForwarding": True, + "ipConfigurations": [ + { + "name": "oezqhkidfhyywlfzwuotilrpbqnjg", + "properties": { + "applicationGatewayBackendAddressPools": [{"id": "groxwd"}], + "applicationSecurityGroups": [{"id": "groxwd"}], + "loadBalancerBackendAddressPools": [{"id": "groxwd"}], + "loadBalancerInboundNatPools": [{"id": "groxwd"}], + "primary": True, + "privateIPAddressVersion": "IPv4", + "publicIPAddressConfiguration": { + "name": "fvpqf", + "properties": { + "deleteOption": "Delete", + "dnsSettings": { + "domainNameLabel": "ukrddzvmorpmfsczjwtbvp", + "domainNameLabelScope": "TenantReuse", + }, + "idleTimeoutInMinutes": 9, + "ipTags": [ + { + "ipTagType": "sddgsoemnzgqizale", + "tag": "wufmhrjsakbiaetyara", + } + ], + "publicIPAddressVersion": "IPv4", + "publicIPPrefix": {"id": "groxwd"}, + }, + "sku": {"name": "Basic", "tier": "Regional"}, + }, + "subnet": {"id": "cmkfcjhmrwxwqtac"}, + }, + } + ], + "networkSecurityGroup": {"id": "groxwd"}, + "primary": True, + }, + } + ], + }, + "osProfile": { + "adminPassword": "adfbrdxpv", + "adminUsername": "nrgzqciiaaxjrqldbmjbqkyhntp", + "allowExtensionOperations": True, + "computerNamePrefix": "o", + "customData": "xjjib", + "linuxConfiguration": { + "disablePasswordAuthentication": True, + "enableVMAgentPlatformUpdates": True, + "patchSettings": { + "assessmentMode": "ImageDefault", + "automaticByPlatformSettings": { + "bypassPlatformSafetyChecksOnUserSchedule": True, + "rebootSetting": "Unknown", + }, + "patchMode": "ImageDefault", + }, + "provisionVMAgent": True, + "ssh": {"publicKeys": [{"keyData": "kivgsubusvpprwqaqpjcmhsv", "path": "kmqz"}]}, + }, + "requireGuestProvisionSignal": True, + "secrets": [ + { + "sourceVault": {"id": "groxwd"}, + "vaultCertificates": [ + { + "certificateStore": "nlxrwavpzhueffxsshlun", + "certificateUrl": "tyldwkzafmnkvpo", + } + ], + } + ], + "windowsConfiguration": { + "additionalUnattendContent": [ + { + "componentName": "Microsoft-Windows-Shell-Setup", + "content": "bubmqbxjkj", + "passName": "OobeSystem", + "settingName": "AutoLogon", + } + ], + "enableAutomaticUpdates": True, + "enableVMAgentPlatformUpdates": True, + "patchSettings": { + "assessmentMode": "ImageDefault", + "automaticByPlatformSettings": { + "bypassPlatformSafetyChecksOnUserSchedule": True, + "rebootSetting": "Unknown", + }, + "enableHotpatching": True, + "patchMode": "Manual", + }, + "provisionVMAgent": True, + "timeZone": "hlyjiqcfksgrpjrct", + "winRM": {"listeners": [{"certificateUrl": "phwesineizrl", "protocol": "Http"}]}, + }, + }, + "priority": "Regular", + "scheduledEventsProfile": { + "osImageNotificationProfile": { + "enable": True, + "notBeforeTimeout": "olbpadmevekyczfokodtfprxti", + }, + "terminateNotificationProfile": {"enable": True, "notBeforeTimeout": "iljppmmw"}, + }, + "securityPostureReference": { + "excludeExtensions": [ + { + "location": "wrqxhbqaebwkzmcdmngyqmhogc", + "properties": { + "autoUpgradeMinorVersion": True, + "enableAutomaticUpgrade": True, + "forceUpdateTag": "oriasdwawveilgusfrn", + "instanceView": { + "name": "ip", + "statuses": [ + { + "code": "kuehuahsdozupmjrtp", + "displayStatus": "pomenhgqjoelbxvsqwxxexqxv", + "level": "Info", + "message": "jxjjmlwbjylzvrislyyflhnmizhiu", + "time": "2024-04-29T21:51:44.042Z", + } + ], + "substatuses": [ + { + "code": "kuehuahsdozupmjrtp", + "displayStatus": "pomenhgqjoelbxvsqwxxexqxv", + "level": "Info", + "message": "jxjjmlwbjylzvrislyyflhnmizhiu", + "time": "2024-04-29T21:51:44.042Z", + } + ], + "type": "woadxvobquacooaujyg", + "typeHandlerVersion": "ftkkqxdqiofgsusvxekdcpua", + }, + "protectedSettings": {}, + "protectedSettingsFromKeyVault": { + "secretUrl": "vyhzfkqsqanacgzjthpjoe", + "sourceVault": {"id": "groxwd"}, + }, + "provisionAfterExtensions": ["lwsfavklrgzuwmyxscskt"], + "publisher": "rxoajzb", + "settings": {}, + "suppressFailures": True, + "type": "vhrtgbaqdkbrrqxsdiiaqxksmqukl", + "typeHandlerVersion": "bvzbiibps", + }, + "tags": {"key7356": "apuftleiygpnemfzryiop"}, + } + ], + "id": "mubredelfbshboaxrsxiajihahaa", + }, + "securityProfile": { + "encryptionAtHost": True, + "encryptionIdentity": {"userAssignedIdentityResourceId": "qoersmt"}, + "proxyAgentSettings": {"enabled": True, "keyIncarnationId": 20, "mode": "Audit"}, + "securityType": "TrustedLaunch", + "uefiSettings": {"secureBootEnabled": True, "vTpmEnabled": True}, + }, + "serviceArtifactReference": {"id": "qlkeeyskyr"}, + "storageProfile": { + "dataDisks": [ + { + "caching": "None", + "createOption": "FromImage", + "deleteOption": "Delete", + "diskIOPSReadWrite": 27, + "diskMBpsReadWrite": 2, + "diskSizeGB": 6, + "lun": 14, + "managedDisk": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityProfile": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityEncryptionType": "VMGuestStateOnly", + }, + "storageAccountType": "Standard_LRS", + }, + "name": "eogiykmdmeikswxmigjws", + "writeAcceleratorEnabled": True, + } + ], + "diskControllerType": "uzb", + "imageReference": { + "communityGalleryImageId": "vlqe", + "id": "aiunknwgksu", + "offer": "isxgumkarlkomp", + "publisher": "mqxgwbiyjzmxavhbkd", + "sharedGalleryImageId": "kmkgihoxwlawuuhcinfirktdwkmx", + "sku": "eojmppqcrnpmxirtp", + "version": "wvpcqefgtmqdgltiuz", + }, + "osDisk": { + "caching": "None", + "createOption": "FromImage", + "deleteOption": "Delete", + "diffDiskSettings": {"option": "Local", "placement": "CacheDisk"}, + "diskSizeGB": 14, + "image": {"uri": "thqceubivdrjs"}, + "managedDisk": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityProfile": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityEncryptionType": "VMGuestStateOnly", + }, + "storageAccountType": "Standard_LRS", + }, + "name": "wfttw", + "osType": "Windows", + "vhdContainers": ["tkzcwddtinkfpnfklatw"], + "writeAcceleratorEnabled": True, + }, + }, + "userData": "s", + }, + "computeApiVersion": "2023-07-01", + "platformFaultDomainCount": 1, + }, + "regularPriorityProfile": {"allocationStrategy": "LowestPrice", "capacity": 20, "minCapacity": 10}, + "spotPriorityProfile": { + "allocationStrategy": "PriceCapacityOptimized", + "capacity": 20, + "evictionPolicy": "Delete", + "maintain": True, + "maxPricePerVM": 0.00865, + "minCapacity": 10, + }, + "vmSizesProfile": [{"name": "Standard_d1_v2", "rank": 19225}], + }, + "tags": {"key3518": "luvrnuvsgdpbuofdskkcoqhfh"}, + "zones": ["zone1", "zone2"], + }, + ).result() + print(response) + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/Fleets_CreateOrUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_delete.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_delete.py new file mode 100644 index 000000000000..3a0f5339380f --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_delete.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python fleets_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="1DC2F28C-A625-4B0E-9748-9885A3C9E9EB", + ) + + client.fleets.begin_delete( + resource_group_name="rgazurefleet", + fleet_name="testFleet", + ).result() + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/Fleets_Delete.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_get.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_get.py new file mode 100644 index 000000000000..e209f676c0e1 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_get.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python fleets_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="1DC2F28C-A625-4B0E-9748-9885A3C9E9EB", + ) + + response = client.fleets.get( + resource_group_name="rgazurefleet", + fleet_name="testFleet", + ) + print(response) + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/Fleets_Get.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_resource_group.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_resource_group.py new file mode 100644 index 000000000000..d3454b4dca2d --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_resource_group.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python fleets_list_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="1DC2F28C-A625-4B0E-9748-9885A3C9E9EB", + ) + + response = client.fleets.list_by_resource_group( + resource_group_name="rgazurefleet", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/Fleets_ListByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_subscription.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_subscription.py new file mode 100644 index 000000000000..3b0ce5b467fa --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_list_by_subscription.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python fleets_list_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="1DC2F28C-A625-4B0E-9748-9885A3C9E9EB", + ) + + response = client.fleets.list_by_subscription() + for item in response: + print(item) + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/Fleets_ListBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_update.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_update.py new file mode 100644 index 000000000000..8603d895db30 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/fleets_update.py @@ -0,0 +1,345 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python fleets_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="1DC2F28C-A625-4B0E-9748-9885A3C9E9EB", + ) + + response = client.fleets.begin_update( + resource_group_name="rgazurefleet", + fleet_name="testFleet", + properties={ + "identity": {"type": "UserAssigned", "userAssignedIdentities": {}}, + "plan": { + "name": "jwgrcrnrtfoxn", + "product": "cgopbyvdyqikahwyxfpzwaqk", + "promotionCode": "naglezezplcaruqogtxnuizslqnnbr", + "publisher": "iozjbiqqckqm", + "version": "wa", + }, + "properties": { + "computeProfile": { + "baseVirtualMachineProfile": { + "applicationProfile": { + "galleryApplications": [ + { + "configurationReference": "ulztmiavpojpbpbddgnuuiimxcpau", + "enableAutomaticUpgrade": True, + "order": 5, + "packageReferenceId": "lfxqiadouhmbovcd", + "tags": "eyrqjbib", + "treatFailureAsDeploymentFailure": True, + } + ] + }, + "billingProfile": {"maxPrice": 2}, + "capacityReservation": {"capacityReservationGroup": {"id": "groxwd"}}, + "diagnosticsProfile": {"bootDiagnostics": {"enabled": True, "storageUri": "rzamfwghybpx"}}, + "evictionPolicy": "Deallocate", + "extensionProfile": { + "extensions": [ + { + "name": "bndxuxx", + "properties": { + "autoUpgradeMinorVersion": True, + "enableAutomaticUpgrade": True, + "forceUpdateTag": "yhgxw", + "protectedSettings": {}, + "protectedSettingsFromKeyVault": { + "secretUrl": "vyhzfkqsqanacgzjthpjoe", + "sourceVault": {"id": "groxwd"}, + }, + "provisionAfterExtensions": ["nftzosroolbcwmpupujzqwqe"], + "publisher": "kpxtirxjfprhs", + "settings": {}, + "suppressFailures": True, + "type": "pgjilctjjwaa", + "typeHandlerVersion": "zevivcoilxmbwlrihhhibq", + }, + } + ], + "extensionsTimeBudget": "mbhjahtdygwgyszdwjtvlvtgchdwil", + }, + "hardwareProfile": {"vmSizeProperties": {"vCPUsAvailable": 16, "vCPUsPerCore": 23}}, + "licenseType": "v", + "networkProfile": { + "healthProbe": {"id": "cmkfcjhmrwxwqtac"}, + "networkApiVersion": "2020-11-01", + "networkInterfaceConfigurations": [ + { + "name": "i", + "properties": { + "auxiliaryMode": "None", + "auxiliarySku": "None", + "deleteOption": "Delete", + "disableTcpStateTracking": True, + "dnsSettings": {"dnsServers": ["nxmmfolhclsesu"]}, + "enableAcceleratedNetworking": True, + "enableFpga": True, + "enableIPForwarding": True, + "ipConfigurations": [ + { + "name": "oezqhkidfhyywlfzwuotilrpbqnjg", + "properties": { + "applicationGatewayBackendAddressPools": [{"id": "groxwd"}], + "applicationSecurityGroups": [{"id": "groxwd"}], + "loadBalancerBackendAddressPools": [{"id": "groxwd"}], + "loadBalancerInboundNatPools": [{"id": "groxwd"}], + "primary": True, + "privateIPAddressVersion": "IPv4", + "publicIPAddressConfiguration": { + "name": "fvpqf", + "properties": { + "deleteOption": "Delete", + "dnsSettings": { + "domainNameLabel": "ukrddzvmorpmfsczjwtbvp", + "domainNameLabelScope": "TenantReuse", + }, + "idleTimeoutInMinutes": 9, + "ipTags": [ + { + "ipTagType": "sddgsoemnzgqizale", + "tag": "wufmhrjsakbiaetyara", + } + ], + "publicIPAddressVersion": "IPv4", + "publicIPPrefix": {"id": "groxwd"}, + }, + "sku": {"name": "Basic", "tier": "Regional"}, + }, + "subnet": {"id": "cmkfcjhmrwxwqtac"}, + }, + } + ], + "networkSecurityGroup": {"id": "groxwd"}, + "primary": True, + }, + } + ], + }, + "osProfile": { + "adminPassword": "adfbrdxpv", + "adminUsername": "nrgzqciiaaxjrqldbmjbqkyhntp", + "allowExtensionOperations": True, + "computerNamePrefix": "o", + "customData": "xjjib", + "linuxConfiguration": { + "disablePasswordAuthentication": True, + "enableVMAgentPlatformUpdates": True, + "patchSettings": { + "assessmentMode": "ImageDefault", + "automaticByPlatformSettings": { + "bypassPlatformSafetyChecksOnUserSchedule": True, + "rebootSetting": "Unknown", + }, + "patchMode": "ImageDefault", + }, + "provisionVMAgent": True, + "ssh": {"publicKeys": [{"keyData": "kivgsubusvpprwqaqpjcmhsv", "path": "kmqz"}]}, + }, + "requireGuestProvisionSignal": True, + "secrets": [ + { + "sourceVault": {"id": "groxwd"}, + "vaultCertificates": [ + { + "certificateStore": "nlxrwavpzhueffxsshlun", + "certificateUrl": "tyldwkzafmnkvpo", + } + ], + } + ], + "windowsConfiguration": { + "additionalUnattendContent": [ + { + "componentName": "Microsoft-Windows-Shell-Setup", + "content": "bubmqbxjkj", + "passName": "OobeSystem", + "settingName": "AutoLogon", + } + ], + "enableAutomaticUpdates": True, + "enableVMAgentPlatformUpdates": True, + "patchSettings": { + "assessmentMode": "ImageDefault", + "automaticByPlatformSettings": { + "bypassPlatformSafetyChecksOnUserSchedule": True, + "rebootSetting": "Unknown", + }, + "enableHotpatching": True, + "patchMode": "Manual", + }, + "provisionVMAgent": True, + "timeZone": "hlyjiqcfksgrpjrct", + "winRM": {"listeners": [{"certificateUrl": "phwesineizrl", "protocol": "Http"}]}, + }, + }, + "priority": "Regular", + "scheduledEventsProfile": { + "osImageNotificationProfile": { + "enable": True, + "notBeforeTimeout": "olbpadmevekyczfokodtfprxti", + }, + "terminateNotificationProfile": {"enable": True, "notBeforeTimeout": "iljppmmw"}, + }, + "securityPostureReference": { + "excludeExtensions": [ + { + "location": "wrqxhbqaebwkzmcdmngyqmhogc", + "properties": { + "autoUpgradeMinorVersion": True, + "enableAutomaticUpgrade": True, + "forceUpdateTag": "oriasdwawveilgusfrn", + "instanceView": { + "name": "ip", + "statuses": [ + { + "code": "kuehuahsdozupmjrtp", + "displayStatus": "pomenhgqjoelbxvsqwxxexqxv", + "level": "Info", + "message": "jxjjmlwbjylzvrislyyflhnmizhiu", + "time": "2024-04-29T21:51:44.042Z", + } + ], + "substatuses": [ + { + "code": "kuehuahsdozupmjrtp", + "displayStatus": "pomenhgqjoelbxvsqwxxexqxv", + "level": "Info", + "message": "jxjjmlwbjylzvrislyyflhnmizhiu", + "time": "2024-04-29T21:51:44.042Z", + } + ], + "type": "woadxvobquacooaujyg", + "typeHandlerVersion": "ftkkqxdqiofgsusvxekdcpua", + }, + "protectedSettings": {}, + "protectedSettingsFromKeyVault": { + "secretUrl": "vyhzfkqsqanacgzjthpjoe", + "sourceVault": {"id": "groxwd"}, + }, + "provisionAfterExtensions": ["lwsfavklrgzuwmyxscskt"], + "publisher": "rxoajzb", + "settings": {}, + "suppressFailures": True, + "type": "vhrtgbaqdkbrrqxsdiiaqxksmqukl", + "typeHandlerVersion": "bvzbiibps", + }, + "tags": {}, + } + ], + "id": "mubredelfbshboaxrsxiajihahaa", + }, + "securityProfile": { + "encryptionAtHost": True, + "encryptionIdentity": {"userAssignedIdentityResourceId": "qoersmt"}, + "proxyAgentSettings": {"enabled": True, "keyIncarnationId": 20, "mode": "Audit"}, + "securityType": "TrustedLaunch", + "uefiSettings": {"secureBootEnabled": True, "vTpmEnabled": True}, + }, + "serviceArtifactReference": {"id": "qlkeeyskyr"}, + "storageProfile": { + "dataDisks": [ + { + "caching": "None", + "createOption": "FromImage", + "deleteOption": "Delete", + "diskIOPSReadWrite": 27, + "diskMBpsReadWrite": 2, + "diskSizeGB": 6, + "lun": 14, + "managedDisk": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityProfile": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityEncryptionType": "VMGuestStateOnly", + }, + "storageAccountType": "Standard_LRS", + }, + "name": "eogiykmdmeikswxmigjws", + "writeAcceleratorEnabled": True, + } + ], + "diskControllerType": "uzb", + "imageReference": { + "communityGalleryImageId": "vlqe", + "id": "aiunknwgksu", + "offer": "isxgumkarlkomp", + "publisher": "mqxgwbiyjzmxavhbkd", + "sharedGalleryImageId": "kmkgihoxwlawuuhcinfirktdwkmx", + "sku": "eojmppqcrnpmxirtp", + "version": "wvpcqefgtmqdgltiuz", + }, + "osDisk": { + "caching": "None", + "createOption": "FromImage", + "deleteOption": "Delete", + "diffDiskSettings": {"option": "Local", "placement": "CacheDisk"}, + "diskSizeGB": 14, + "image": {"uri": "thqceubivdrjs"}, + "managedDisk": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityProfile": { + "diskEncryptionSet": {"id": "vmatqblzjalbatdepyzqmnd"}, + "securityEncryptionType": "VMGuestStateOnly", + }, + "storageAccountType": "Standard_LRS", + }, + "name": "wfttw", + "osType": "Windows", + "vhdContainers": ["tkzcwddtinkfpnfklatw"], + "writeAcceleratorEnabled": True, + }, + }, + "userData": "s", + }, + "computeApiVersion": "2023-07-01", + "platformFaultDomainCount": 1, + }, + "regularPriorityProfile": {"allocationStrategy": "LowestPrice", "capacity": 20, "minCapacity": 10}, + "spotPriorityProfile": { + "allocationStrategy": "PriceCapacityOptimized", + "capacity": 20, + "evictionPolicy": "Delete", + "maintain": True, + "maxPricePerVM": 0.00865, + "minCapacity": 10, + }, + "vmSizesProfile": [{"name": "Standard_d1_v2", "rank": 19225}], + }, + "tags": {}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/Fleets_Update.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/operations_list.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/operations_list.py new file mode 100644 index 000000000000..5b3092eb09ac --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/operations_list.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python operations_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.operations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/Operations_List.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/generated_samples/virtual_machine_scale_sets_list_by_fleet.py b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/virtual_machine_scale_sets_list_by_fleet.py new file mode 100644 index 000000000000..bb9627f7c48e --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/generated_samples/virtual_machine_scale_sets_list_by_fleet.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.computefleet import MicrosoftAzureFleet + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-computefleet +# USAGE + python virtual_machine_scale_sets_list_by_fleet.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MicrosoftAzureFleet( + credential=DefaultAzureCredential(), + subscription_id="7B0CD4DB-3381-4013-9B31-FB6E6FD0FF1C", + ) + + response = client.virtual_machine_scale_sets.list_by_fleet( + resource_group_name="rgazurefleet", + name="myFleet", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/azurefleet/resource-manager/Microsoft.AzureFleet/preview/2024-05-01-preview/examples/VirtualMachineScaleSets_ListByFleet.json +if __name__ == "__main__": + main() diff --git a/sdk/computefleet/azure-mgmt-computefleet/sdk_packaging.toml b/sdk/computefleet/azure-mgmt-computefleet/sdk_packaging.toml new file mode 100644 index 000000000000..38206c20bc22 --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/sdk_packaging.toml @@ -0,0 +1,11 @@ +[packaging] +package_name = "azure-mgmt-computefleet" +package_nspkg = "azure-mgmt-nspkg" +package_pprint_name = "MyService Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" diff --git a/sdk/computefleet/azure-mgmt-computefleet/setup.py b/sdk/computefleet/azure-mgmt-computefleet/setup.py new file mode 100644 index 000000000000..2fa2e30a2c2d --- /dev/null +++ b/sdk/computefleet/azure-mgmt-computefleet/setup.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import re +import os.path +from io import open +from setuptools import find_packages, setup + +# Change the PACKAGE_NAME only to change folder and different name +PACKAGE_NAME = "azure-mgmt-computefleet" +PACKAGE_PPRINT_NAME = "MyService Management" + +# a-b-c => a/b/c +package_folder_path = PACKAGE_NAME.replace("-", "/") +# a-b-c => a.b.c +namespace_name = PACKAGE_NAME.replace("-", ".") + +# Version extraction inspired from 'requests' +with open( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else 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") + +with open("README.md", encoding="utf-8") as f: + readme = f.read() +with open("CHANGELOG.md", encoding="utf-8") as f: + changelog = f.read() + +setup( + name=PACKAGE_NAME, + version=version, + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + 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", + keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product + classifiers=[ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "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.mgmt", + ] + ), + include_package_data=True, + package_data={ + "pytyped": ["py.typed"], + }, + install_requires=[ + "isodate>=0.6.1", + "azure-common>=1.1", + "azure-mgmt-core>=1.3.2", + ], + python_requires=">=3.8", +) diff --git a/sdk/computefleet/ci.yml b/sdk/computefleet/ci.yml new file mode 100644 index 000000000000..fa2a2c12c572 --- /dev/null +++ b/sdk/computefleet/ci.yml @@ -0,0 +1,34 @@ +# DO NOT EDIT THIS FILE +# This file is generated automatically and any changes will be lost. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/computefleet/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/computefleet/ + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: computefleet + TestProxy: true + Artifacts: + - name: azure-mgmt-computefleet + safeName: azuremgmtcomputefleet diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/CHANGELOG.md b/sdk/mongocluster/azure-mgmt-mongocluster/CHANGELOG.md new file mode 100644 index 000000000000..578ed6acf479 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 0.1.0 (1970-01-01) + +* Initial Release diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/LICENSE b/sdk/mongocluster/azure-mgmt-mongocluster/LICENSE new file mode 100644 index 000000000000..b2f52a2bad4e --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/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. diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/MANIFEST.in b/sdk/mongocluster/azure-mgmt-mongocluster/MANIFEST.in new file mode 100644 index 000000000000..bc608254569a --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/MANIFEST.in @@ -0,0 +1,8 @@ +include _meta.json +recursive-include tests *.py *.json +recursive-include samples *.py *.md +include *.md +include azure/__init__.py +include azure/mgmt/__init__.py +include LICENSE +include azure/mgmt/mongocluster/py.typed diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/README.md b/sdk/mongocluster/azure-mgmt-mongocluster/README.md new file mode 100644 index 000000000000..7478dc9e46c0 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/README.md @@ -0,0 +1,61 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure MyService Management Client Library. +This package has been tested with Python 3.8+. +For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ + +## Getting started + +### Prerequisites + +- Python 3.8+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) + +### Install the package + +```bash +pip install azure-mgmt-mongocluster +pip install azure-identity +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configure of following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.mongocluster import +import os + +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = (credential=DefaultAzureCredential(), subscription_id=sub_id) +``` + +## Examples + +Code samples for this package can be found at: +- [Search MyService Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/_meta.json b/sdk/mongocluster/azure-mgmt-mongocluster/_meta.json new file mode 100644 index 000000000000..284ce26c6e97 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/_meta.json @@ -0,0 +1,11 @@ +{ + "commit": "293ac41c07fad031af73b7290797c6c3e784d8ac", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.13.19", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/mongocluster/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.13.19 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/mongocluster/resource-manager/readme.md" +} \ No newline at end of file diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/__init__.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/__init__.py new file mode 100644 index 000000000000..8db66d3d0f0f --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/__init__.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/__init__.py new file mode 100644 index 000000000000..8db66d3d0f0f --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/__init__.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/__init__.py new file mode 100644 index 000000000000..ffc02131c17f --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/__init__.py @@ -0,0 +1,26 @@ +# 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 ._mongo_cluster_management_client import MongoClusterManagementClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "MongoClusterManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_configuration.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_configuration.py new file mode 100644 index 000000000000..cacbf4b6d940 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_configuration.py @@ -0,0 +1,65 @@ +# 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.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MongoClusterManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for MongoClusterManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-03-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-mongocluster/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_mongo_cluster_management_client.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_mongo_cluster_management_client.py new file mode 100644 index 000000000000..4b2a81d66332 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_mongo_cluster_management_client.py @@ -0,0 +1,133 @@ +# 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.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy + +from . import models as _models +from ._configuration import MongoClusterManagementClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + FirewallRulesOperations, + MongoClustersOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinksOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MongoClusterManagementClient: # pylint: disable=client-accepts-api-version-keyword + """The Microsoft Azure management API provides create, read, update, and delete functionality for + Azure Cosmos DB for MongoDB vCore resources including clusters and firewall rules. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.mongocluster.operations.Operations + :ivar mongo_clusters: MongoClustersOperations operations + :vartype mongo_clusters: azure.mgmt.mongocluster.operations.MongoClustersOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.mongocluster.operations.FirewallRulesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.mongocluster.operations.PrivateEndpointConnectionsOperations + :ivar private_links: PrivateLinksOperations operations + :vartype private_links: azure.mgmt.mongocluster.operations.PrivateLinksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2024-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, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MongoClusterManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.mongo_clusters = MongoClustersOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_links = PrivateLinksOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, request: HttpRequest, *, stream: bool = False, **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) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "MongoClusterManagementClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_patch.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_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/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_serialization.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_serialization.py new file mode 100644 index 000000000000..f0c6180722c8 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_serialization.py @@ -0,0 +1,1998 @@ +# -------------------------------------------------------------------------- +# +# 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 +# pyright: reportUnnecessaryTypeIgnoreComment=false + +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 +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] + + +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: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> 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 as err: + # 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 DeserializationError("XML is invalid") from err + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: 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 + + +_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 # type: ignore +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 +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[Dict[str, Any]] = {} + for k in kwargs: + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node.""" + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result.update(objects[valuetype]._flatten_subtype(key, objects)) + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + Remove the polymorphic key from the initial data. + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + """ + return key.replace("\\.", ".") + + +class Serializer(object): + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > 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: Optional[Mapping[str, type]] = 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[str, type] = 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) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + 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) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from 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_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, 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 = [ # type: ignore + 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 SerializationError("Unable to build a model: " + str(err)) from 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) + output = output.replace("{", quote("{")).replace("}", quote("}")) + 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. + :keyword bool skip_quote: Whether to skip quote the serialized result. + Defaults to False. + :rtype: str, list + :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] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **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 is CoreNull: + return None + 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 SerializationError(msg.format(data, data_type)) from 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): # type: ignore + # 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'. + :keyword bool do_quote: Whether to quote the serialized result of each iterable element. + Defaults to False. + :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 as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + 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 as err: + if isinstance(err, SerializationError): + raise + 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 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) # type: ignore + return result + except ValueError: + for enum_value in enum_obj: # type: ignore + 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 SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from 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: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _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 + 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 + 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: Optional[Mapping[str, type]] = 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[str, type] = 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, str): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore + 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 # type: ignore + raise DeserializationError(msg) from 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 deserialize. + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + 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 deserialize. + :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, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + 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) # type: ignore + 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 DeserializationError(msg) from 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, str): + 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, str): + 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): # type: ignore + 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. + 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)) # type: ignore + + @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) # type: ignore + attr = attr + padding # type: ignore + 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(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from 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) # type: ignore + + @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 DeserializationError(msg) from 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): # type: ignore + 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=0, defaultday=0) + + @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): # type: ignore + 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) # type: ignore + 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 DeserializationError(msg) from 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() # type: ignore + 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 DeserializationError(msg) from 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) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + else: + return date_obj diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_vendor.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_vendor.py new file mode 100644 index 000000000000..0dafe0e287ff --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_vendor.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_version.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/_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/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/__init__.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/__init__.py new file mode 100644 index 000000000000..e3d7f999c94c --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/__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 ._mongo_cluster_management_client import MongoClusterManagementClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "MongoClusterManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_configuration.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_configuration.py new file mode 100644 index 000000000000..efe50f91e6e5 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_configuration.py @@ -0,0 +1,65 @@ +# 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.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MongoClusterManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for MongoClusterManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-03-01-preview") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-mongocluster/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_mongo_cluster_management_client.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_mongo_cluster_management_client.py new file mode 100644 index 000000000000..7c87f117fe39 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_mongo_cluster_management_client.py @@ -0,0 +1,135 @@ +# 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.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy + +from .. import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import MongoClusterManagementClientConfiguration +from .operations import ( + FirewallRulesOperations, + MongoClustersOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinksOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MongoClusterManagementClient: # pylint: disable=client-accepts-api-version-keyword + """The Microsoft Azure management API provides create, read, update, and delete functionality for + Azure Cosmos DB for MongoDB vCore resources including clusters and firewall rules. + + :ivar operations: Operations operations + :vartype operations: azure.mgmt.mongocluster.aio.operations.Operations + :ivar mongo_clusters: MongoClustersOperations operations + :vartype mongo_clusters: azure.mgmt.mongocluster.aio.operations.MongoClustersOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.mongocluster.aio.operations.FirewallRulesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.mongocluster.aio.operations.PrivateEndpointConnectionsOperations + :ivar private_links: PrivateLinksOperations operations + :vartype private_links: azure.mgmt.mongocluster.aio.operations.PrivateLinksOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2024-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, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MongoClusterManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.mongo_clusters = MongoClustersOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_links = PrivateLinksOperations(self._client, self._config, self._serialize, self._deserialize) + + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **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) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MongoClusterManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_patch.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/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/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/__init__.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/__init__.py new file mode 100644 index 000000000000..3300f25ba7be --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/__init__.py @@ -0,0 +1,27 @@ +# 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 Operations +from ._mongo_clusters_operations import MongoClustersOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_links_operations import PrivateLinksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "MongoClustersOperations", + "FirewallRulesOperations", + "PrivateEndpointConnectionsOperations", + "PrivateLinksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_firewall_rules_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_firewall_rules_operations.py new file mode 100644 index 000000000000..68255cda7fae --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_firewall_rules_operations.py @@ -0,0 +1,536 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._firewall_rules_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_mongo_cluster_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class FirewallRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.aio.MongoClusterManagementClient`'s + :attr:`firewall_rules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_mongo_cluster( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> AsyncIterable["_models.FirewallRule"]: + """List all the firewall rules in a given mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An iterator like instance of either FirewallRule or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FirewallRuleListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_mongo_cluster_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("FirewallRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, **kwargs: Any + ) -> _models.FirewallRule: + """Gets information about a mongo cluster firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :return: FirewallRule or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.FirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FirewallRule] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FirewallRule", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: Union[_models.FirewallRule, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.FirewallRule]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.FirewallRule]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "FirewallRule") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("FirewallRule", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("FirewallRule", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: _models.FirewallRule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.mongocluster.models.FirewallRule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: Union[_models.FirewallRule, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :param resource: Resource create parameters. Is either a FirewallRule type or a IO[bytes] type. + Required. + :type resource: ~azure.mgmt.mongocluster.models.FirewallRule or IO[bytes] + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.FirewallRule] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("FirewallRule", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.FirewallRule].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.FirewallRule]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a mongo cluster firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_mongo_clusters_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_mongo_clusters_operations.py new file mode 100644 index 000000000000..7c4671e1373b --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_mongo_clusters_operations.py @@ -0,0 +1,962 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._mongo_clusters_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_connection_strings_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class MongoClustersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.aio.MongoClusterManagementClient`'s + :attr:`mongo_clusters` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def check_name_availability( + self, + location: str, + body: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Check if mongo cluster name is available for use. + + :param location: The name of the Azure region. Required. + :type location: str + :param body: The CheckAvailability request. Required. + :type body: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, location: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Check if mongo cluster name is available for use. + + :param location: The name of the Azure region. Required. + :type location: str + :param body: The CheckAvailability request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, body: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Check if mongo cluster name is available for use. + + :param location: The name of the Azure region. Required. + :type location: str + :param body: The CheckAvailability request. Is either a CheckNameAvailabilityRequest type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityRequest or IO[bytes] + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameAvailabilityResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CheckNameAvailabilityRequest") + + _request = build_check_name_availability_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.MongoCluster"]: + """List all the mongo clusters in a given subscription. + + :return: An iterator like instance of either MongoCluster or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoClusterListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MongoClusterListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.MongoCluster"]: + """List all the mongo clusters in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either MongoCluster or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoClusterListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("MongoClusterListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any) -> _models.MongoCluster: + """Gets information about a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: MongoCluster or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.MongoCluster + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: Union[_models.MongoCluster, IO[bytes]], + **kwargs: Any + ) -> _models.MongoCluster: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "MongoCluster") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if response.status_code == 201: + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: _models.MongoCluster, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoCluster]: + """Create or update a mongo cluster. Update overwrites all properties for the resource. To only + modify some of the properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.mongocluster.models.MongoCluster + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoCluster]: + """Create or update a mongo cluster. Update overwrites all properties for the resource. To only + modify some of the properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: Union[_models.MongoCluster, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoCluster]: + """Create or update a mongo cluster. Update overwrites all properties for the resource. To only + modify some of the properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param resource: Resource create parameters. Is either a MongoCluster type or a IO[bytes] type. + Required. + :type resource: ~azure.mgmt.mongocluster.models.MongoCluster or IO[bytes] + :return: An instance of AsyncLROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoCluster", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.MongoCluster].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.MongoCluster]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: Union[_models.MongoClusterUpdate, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.MongoCluster]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.MongoCluster]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "MongoClusterUpdate") + + _request = build_update_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: _models.MongoClusterUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoCluster]: + """Updates an existing mongo cluster. The request body can contain one to many of the properties + present in the normal mongo cluster definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.mongocluster.models.MongoClusterUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoCluster]: + """Updates an existing mongo cluster. The request body can contain one to many of the properties + present in the normal mongo cluster definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: Union[_models.MongoClusterUpdate, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.MongoCluster]: + """Updates an existing mongo cluster. The request body can contain one to many of the properties + present in the normal mongo cluster definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param properties: The resource properties to be updated. Is either a MongoClusterUpdate type + or a IO[bytes] type. Required. + :type properties: ~azure.mgmt.mongocluster.models.MongoClusterUpdate or IO[bytes] + :return: An instance of AsyncLROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + properties=properties, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoCluster", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.MongoCluster].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.MongoCluster]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def list_connection_strings( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> _models.ListConnectionStringsResult: + """List mongo cluster connection strings. This includes the default connection string using + SCRAM-SHA-256, as well as other connection strings supported by the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: ListConnectionStringsResult or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.ListConnectionStringsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListConnectionStringsResult] = kwargs.pop("cls", None) + + _request = build_list_connection_strings_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ListConnectionStringsResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_operations.py new file mode 100644 index 000000000000..bee7c557dd59 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_operations.py @@ -0,0 +1,134 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.aio.MongoClusterManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.mongocluster.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_patch.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/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/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_endpoint_connections_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_endpoint_connections_operations.py new file mode 100644 index 000000000000..b373c1815161 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,546 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._private_endpoint_connections_operations import ( + build_create_request, + build_delete_request, + build_get_request, + build_list_by_mongo_cluster_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.aio.MongoClusterManagementClient`'s + :attr:`private_endpoint_connections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_mongo_cluster( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateEndpointConnectionResource"]: + """List existing private connections. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An iterator like instance of either PrivateEndpointConnectionResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnectionResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_mongo_cluster_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get( + self, resource_group_name: str, mongo_cluster_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionResource: + """Get a specific private connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: PrivateEndpointConnectionResource or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnectionResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: Union[_models.PrivateEndpointConnectionResource, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.PrivateEndpointConnectionResource]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.PrivateEndpointConnectionResource]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "PrivateEndpointConnectionResource") + + _request = build_create_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: _models.PrivateEndpointConnectionResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnectionResource]: + """Create a Private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnectionResource or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnectionResource]: + """Create a Private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnectionResource or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: Union[_models.PrivateEndpointConnectionResource, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnectionResource]: + """Create a Private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param resource: Resource create parameters. Is either a PrivateEndpointConnectionResource type + or a IO[bytes] type. Required. + :type resource: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource or IO[bytes] + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnectionResource or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnectionResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.PrivateEndpointConnectionResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PrivateEndpointConnectionResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, mongo_cluster_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, mongo_cluster_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Delete the private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_links_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_links_operations.py new file mode 100644 index 000000000000..6781e769dcd5 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/aio/operations/_private_links_operations.py @@ -0,0 +1,145 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._private_links_operations import build_list_by_mongo_cluster_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PrivateLinksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.aio.MongoClusterManagementClient`'s + :attr:`private_links` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_mongo_cluster( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateLinkResource"]: + """list private links on the given resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.mongocluster.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_mongo_cluster_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/__init__.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/__init__.py new file mode 100644 index 000000000000..a27b5f528d8e --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/__init__.py @@ -0,0 +1,107 @@ +# 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 ._models_py3 import CheckNameAvailabilityRequest +from ._models_py3 import CheckNameAvailabilityResponse +from ._models_py3 import ConnectionString +from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorResponse +from ._models_py3 import FirewallRule +from ._models_py3 import FirewallRuleListResult +from ._models_py3 import FirewallRuleProperties +from ._models_py3 import ListConnectionStringsResult +from ._models_py3 import MongoCluster +from ._models_py3 import MongoClusterListResult +from ._models_py3 import MongoClusterProperties +from ._models_py3 import MongoClusterRestoreParameters +from ._models_py3 import MongoClusterUpdate +from ._models_py3 import MongoClusterUpdateProperties +from ._models_py3 import NodeGroupProperties +from ._models_py3 import NodeGroupSpec +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import PrivateEndpoint +from ._models_py3 import PrivateEndpointConnection +from ._models_py3 import PrivateEndpointConnectionProperties +from ._models_py3 import PrivateEndpointConnectionResource +from ._models_py3 import PrivateEndpointConnectionResourceListResult +from ._models_py3 import PrivateLinkResource +from ._models_py3 import PrivateLinkResourceListResult +from ._models_py3 import PrivateLinkResourceProperties +from ._models_py3 import PrivateLinkServiceConnectionState +from ._models_py3 import ProxyResource +from ._models_py3 import Resource +from ._models_py3 import SystemData +from ._models_py3 import TrackedResource + +from ._mongo_cluster_management_client_enums import ActionType +from ._mongo_cluster_management_client_enums import CheckNameAvailabilityReason +from ._mongo_cluster_management_client_enums import CreateMode +from ._mongo_cluster_management_client_enums import CreatedByType +from ._mongo_cluster_management_client_enums import MongoClusterStatus +from ._mongo_cluster_management_client_enums import NodeKind +from ._mongo_cluster_management_client_enums import Origin +from ._mongo_cluster_management_client_enums import PrivateEndpointConnectionProvisioningState +from ._mongo_cluster_management_client_enums import PrivateEndpointServiceConnectionStatus +from ._mongo_cluster_management_client_enums import ProvisioningState +from ._mongo_cluster_management_client_enums import PublicNetworkAccess +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "CheckNameAvailabilityRequest", + "CheckNameAvailabilityResponse", + "ConnectionString", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "FirewallRule", + "FirewallRuleListResult", + "FirewallRuleProperties", + "ListConnectionStringsResult", + "MongoCluster", + "MongoClusterListResult", + "MongoClusterProperties", + "MongoClusterRestoreParameters", + "MongoClusterUpdate", + "MongoClusterUpdateProperties", + "NodeGroupProperties", + "NodeGroupSpec", + "Operation", + "OperationDisplay", + "OperationListResult", + "PrivateEndpoint", + "PrivateEndpointConnection", + "PrivateEndpointConnectionProperties", + "PrivateEndpointConnectionResource", + "PrivateEndpointConnectionResourceListResult", + "PrivateLinkResource", + "PrivateLinkResourceListResult", + "PrivateLinkResourceProperties", + "PrivateLinkServiceConnectionState", + "ProxyResource", + "Resource", + "SystemData", + "TrackedResource", + "ActionType", + "CheckNameAvailabilityReason", + "CreateMode", + "CreatedByType", + "MongoClusterStatus", + "NodeKind", + "Origin", + "PrivateEndpointConnectionProvisioningState", + "PrivateEndpointServiceConnectionStatus", + "ProvisioningState", + "PublicNetworkAccess", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_models_py3.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_models_py3.py new file mode 100644 index 000000000000..94d06172e8b6 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_models_py3.py @@ -0,0 +1,1449 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from .. import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class CheckNameAvailabilityRequest(_serialization.Model): + """The check availability request body. + + :ivar name: The name of the resource for which availability needs to be checked. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: The name of the resource for which availability needs to be checked. + :paramtype name: str + :keyword type: The resource type. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class CheckNameAvailabilityResponse(_serialization.Model): + """The check availability result. + + :ivar name_available: Indicates if the resource name is available. + :vartype name_available: bool + :ivar reason: The reason why the given name is not available. Known values are: "Invalid" and + "AlreadyExists". + :vartype reason: str or ~azure.mgmt.mongocluster.models.CheckNameAvailabilityReason + :ivar message: Detailed reason why the given name is available. + :vartype message: str + """ + + _attribute_map = { + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__( + self, + *, + name_available: Optional[bool] = None, + reason: Optional[Union[str, "_models.CheckNameAvailabilityReason"]] = None, + message: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name_available: Indicates if the resource name is available. + :paramtype name_available: bool + :keyword reason: The reason why the given name is not available. Known values are: "Invalid" + and "AlreadyExists". + :paramtype reason: str or ~azure.mgmt.mongocluster.models.CheckNameAvailabilityReason + :keyword message: Detailed reason why the given name is available. + :paramtype message: str + """ + super().__init__(**kwargs) + self.name_available = name_available + self.reason = reason + self.message = message + + +class ConnectionString(_serialization.Model): + """Connection string for the mongo cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar connection_string: Value of the connection string. + :vartype connection_string: str + :ivar description: Description of the connection string. + :vartype description: str + """ + + _validation = { + "connection_string": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "connection_string": {"key": "connectionString", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.connection_string = None + self.description = None + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.mongocluster.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.mongocluster.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.mongocluster.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.mongocluster.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have + tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + """ + + +class FirewallRule(ProxyResource): + """Represents a mongo cluster firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.mongocluster.models.FirewallRuleProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "FirewallRuleProperties"}, + } + + def __init__(self, *, properties: Optional["_models.FirewallRuleProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: The resource-specific properties for this resource. + :paramtype properties: ~azure.mgmt.mongocluster.models.FirewallRuleProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class FirewallRuleListResult(_serialization.Model): + """The response of a FirewallRule list operation. + + All required parameters must be populated in order to send to server. + + :ivar value: The FirewallRule items on this page. Required. + :vartype value: list[~azure.mgmt.mongocluster.models.FirewallRule] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[FirewallRule]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: List["_models.FirewallRule"], next_link: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword value: The FirewallRule items on this page. Required. + :paramtype value: list[~azure.mgmt.mongocluster.models.FirewallRule] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class FirewallRuleProperties(_serialization.Model): + """The properties of a mongo cluster firewall rule. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar provisioning_state: The provisioning state of the firewall rule. Known values are: + "Succeeded", "Failed", "Canceled", "InProgress", "Updating", and "Dropping". + :vartype provisioning_state: str or ~azure.mgmt.mongocluster.models.ProvisioningState + :ivar start_ip_address: The start IP address of the mongo cluster firewall rule. Must be IPv4 + format. Required. + :vartype start_ip_address: str + :ivar end_ip_address: The end IP address of the mongo cluster firewall rule. Must be IPv4 + format. Required. + :vartype end_ip_address: str + """ + + _validation = { + "provisioning_state": {"readonly": True}, + "start_ip_address": { + "required": True, + "pattern": r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", + }, + "end_ip_address": { + "required": True, + "pattern": r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", + }, + } + + _attribute_map = { + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "start_ip_address": {"key": "startIpAddress", "type": "str"}, + "end_ip_address": {"key": "endIpAddress", "type": "str"}, + } + + def __init__(self, *, start_ip_address: str, end_ip_address: str, **kwargs: Any) -> None: + """ + :keyword start_ip_address: The start IP address of the mongo cluster firewall rule. Must be + IPv4 format. Required. + :paramtype start_ip_address: str + :keyword end_ip_address: The end IP address of the mongo cluster firewall rule. Must be IPv4 + format. Required. + :paramtype end_ip_address: str + """ + super().__init__(**kwargs) + self.provisioning_state = None + self.start_ip_address = start_ip_address + self.end_ip_address = end_ip_address + + +class ListConnectionStringsResult(_serialization.Model): + """The connection strings for the given mongo cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar connection_strings: An array that contains the connection strings for a mongo cluster. + :vartype connection_strings: list[~azure.mgmt.mongocluster.models.ConnectionString] + """ + + _validation = { + "connection_strings": {"readonly": True}, + } + + _attribute_map = { + "connection_strings": {"key": "connectionStrings", "type": "[ConnectionString]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.connection_strings = None + + +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which + has 'tags' and a 'location'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + } + + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + """ + super().__init__(**kwargs) + self.tags = tags + self.location = location + + +class MongoCluster(TrackedResource): + """Represents a mongo cluster resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.mongocluster.models.MongoClusterProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "properties": {"key": "properties", "type": "MongoClusterProperties"}, + } + + def __init__( + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + properties: Optional["_models.MongoClusterProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + :keyword properties: The resource-specific properties for this resource. + :paramtype properties: ~azure.mgmt.mongocluster.models.MongoClusterProperties + """ + super().__init__(tags=tags, location=location, **kwargs) + self.properties = properties + + +class MongoClusterListResult(_serialization.Model): + """The response of a MongoCluster list operation. + + All required parameters must be populated in order to send to server. + + :ivar value: The MongoCluster items on this page. Required. + :vartype value: list[~azure.mgmt.mongocluster.models.MongoCluster] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[MongoCluster]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: List["_models.MongoCluster"], next_link: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword value: The MongoCluster items on this page. Required. + :paramtype value: list[~azure.mgmt.mongocluster.models.MongoCluster] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class MongoClusterProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The properties of a mongo cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar create_mode: The mode to create a mongo cluster. Known values are: "Default" and + "PointInTimeRestore". + :vartype create_mode: str or ~azure.mgmt.mongocluster.models.CreateMode + :ivar restore_parameters: The parameters to create a point-in-time restore mongo cluster. + :vartype restore_parameters: ~azure.mgmt.mongocluster.models.MongoClusterRestoreParameters + :ivar administrator_login: The administrator's login for the mongo cluster. + :vartype administrator_login: str + :ivar administrator_login_password: The password of the administrator login. + :vartype administrator_login_password: str + :ivar server_version: The Mongo DB server version. Defaults to the latest available version if + not specified. + :vartype server_version: str + :ivar connection_string: The default mongo connection string for the cluster. + :vartype connection_string: str + :ivar earliest_restore_time: Earliest restore timestamp in UTC ISO8601 format. + :vartype earliest_restore_time: str + :ivar provisioning_state: The provisioning state of the mongo cluster. Known values are: + "Succeeded", "Failed", "Canceled", "InProgress", "Updating", and "Dropping". + :vartype provisioning_state: str or ~azure.mgmt.mongocluster.models.ProvisioningState + :ivar cluster_status: The status of the mongo cluster. Known values are: "Ready", + "Provisioning", "Updating", "Starting", "Stopping", "Stopped", and "Dropping". + :vartype cluster_status: str or ~azure.mgmt.mongocluster.models.MongoClusterStatus + :ivar public_network_access: Whether or not public endpoint access is allowed for this mongo + cluster. Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or ~azure.mgmt.mongocluster.models.PublicNetworkAccess + :ivar node_group_specs: The list of node group specs in the cluster. + :vartype node_group_specs: list[~azure.mgmt.mongocluster.models.NodeGroupSpec] + :ivar private_endpoint_connections: List of private endpoint connections. + :vartype private_endpoint_connections: + list[~azure.mgmt.mongocluster.models.PrivateEndpointConnection] + """ + + _validation = { + "connection_string": {"readonly": True}, + "earliest_restore_time": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "cluster_status": {"readonly": True}, + "private_endpoint_connections": {"readonly": True}, + } + + _attribute_map = { + "create_mode": {"key": "createMode", "type": "str"}, + "restore_parameters": {"key": "restoreParameters", "type": "MongoClusterRestoreParameters"}, + "administrator_login": {"key": "administratorLogin", "type": "str"}, + "administrator_login_password": {"key": "administratorLoginPassword", "type": "str"}, + "server_version": {"key": "serverVersion", "type": "str"}, + "connection_string": {"key": "connectionString", "type": "str"}, + "earliest_restore_time": {"key": "earliestRestoreTime", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "cluster_status": {"key": "clusterStatus", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "node_group_specs": {"key": "nodeGroupSpecs", "type": "[NodeGroupSpec]"}, + "private_endpoint_connections": {"key": "privateEndpointConnections", "type": "[PrivateEndpointConnection]"}, + } + + def __init__( + self, + *, + create_mode: Optional[Union[str, "_models.CreateMode"]] = None, + restore_parameters: Optional["_models.MongoClusterRestoreParameters"] = None, + administrator_login: Optional[str] = None, + administrator_login_password: Optional[str] = None, + server_version: Optional[str] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + node_group_specs: Optional[List["_models.NodeGroupSpec"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword create_mode: The mode to create a mongo cluster. Known values are: "Default" and + "PointInTimeRestore". + :paramtype create_mode: str or ~azure.mgmt.mongocluster.models.CreateMode + :keyword restore_parameters: The parameters to create a point-in-time restore mongo cluster. + :paramtype restore_parameters: ~azure.mgmt.mongocluster.models.MongoClusterRestoreParameters + :keyword administrator_login: The administrator's login for the mongo cluster. + :paramtype administrator_login: str + :keyword administrator_login_password: The password of the administrator login. + :paramtype administrator_login_password: str + :keyword server_version: The Mongo DB server version. Defaults to the latest available version + if not specified. + :paramtype server_version: str + :keyword public_network_access: Whether or not public endpoint access is allowed for this mongo + cluster. Known values are: "Enabled" and "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.mongocluster.models.PublicNetworkAccess + :keyword node_group_specs: The list of node group specs in the cluster. + :paramtype node_group_specs: list[~azure.mgmt.mongocluster.models.NodeGroupSpec] + """ + super().__init__(**kwargs) + self.create_mode = create_mode + self.restore_parameters = restore_parameters + self.administrator_login = administrator_login + self.administrator_login_password = administrator_login_password + self.server_version = server_version + self.connection_string = None + self.earliest_restore_time = None + self.provisioning_state = None + self.cluster_status = None + self.public_network_access = public_network_access + self.node_group_specs = node_group_specs + self.private_endpoint_connections = None + + +class MongoClusterRestoreParameters(_serialization.Model): + """Parameters used for restore operations. + + :ivar point_in_time_utc: UTC point in time to restore a mongo cluster. + :vartype point_in_time_utc: ~datetime.datetime + :ivar source_resource_id: Resource ID to locate the source cluster to restore. + :vartype source_resource_id: str + """ + + _attribute_map = { + "point_in_time_utc": {"key": "pointInTimeUTC", "type": "iso-8601"}, + "source_resource_id": {"key": "sourceResourceId", "type": "str"}, + } + + def __init__( + self, + *, + point_in_time_utc: Optional[datetime.datetime] = None, + source_resource_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword point_in_time_utc: UTC point in time to restore a mongo cluster. + :paramtype point_in_time_utc: ~datetime.datetime + :keyword source_resource_id: Resource ID to locate the source cluster to restore. + :paramtype source_resource_id: str + """ + super().__init__(**kwargs) + self.point_in_time_utc = point_in_time_utc + self.source_resource_id = source_resource_id + + +class MongoClusterUpdate(_serialization.Model): + """The type used for update operations of the MongoCluster. + + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: The updatable properties of the MongoCluster. + :vartype properties: ~azure.mgmt.mongocluster.models.MongoClusterUpdateProperties + """ + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + "properties": {"key": "properties", "type": "MongoClusterUpdateProperties"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + properties: Optional["_models.MongoClusterUpdateProperties"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword properties: The updatable properties of the MongoCluster. + :paramtype properties: ~azure.mgmt.mongocluster.models.MongoClusterUpdateProperties + """ + super().__init__(**kwargs) + self.tags = tags + self.properties = properties + + +class MongoClusterUpdateProperties(_serialization.Model): + """The updatable properties of the MongoCluster. + + :ivar administrator_login: The administrator's login for the mongo cluster. + :vartype administrator_login: str + :ivar administrator_login_password: The password of the administrator login. + :vartype administrator_login_password: str + :ivar server_version: The Mongo DB server version. Defaults to the latest available version if + not specified. + :vartype server_version: str + :ivar public_network_access: Whether or not public endpoint access is allowed for this mongo + cluster. Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or ~azure.mgmt.mongocluster.models.PublicNetworkAccess + :ivar node_group_specs: The list of node group specs in the cluster. + :vartype node_group_specs: list[~azure.mgmt.mongocluster.models.NodeGroupSpec] + """ + + _attribute_map = { + "administrator_login": {"key": "administratorLogin", "type": "str"}, + "administrator_login_password": {"key": "administratorLoginPassword", "type": "str"}, + "server_version": {"key": "serverVersion", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "node_group_specs": {"key": "nodeGroupSpecs", "type": "[NodeGroupSpec]"}, + } + + def __init__( + self, + *, + administrator_login: Optional[str] = None, + administrator_login_password: Optional[str] = None, + server_version: Optional[str] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + node_group_specs: Optional[List["_models.NodeGroupSpec"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword administrator_login: The administrator's login for the mongo cluster. + :paramtype administrator_login: str + :keyword administrator_login_password: The password of the administrator login. + :paramtype administrator_login_password: str + :keyword server_version: The Mongo DB server version. Defaults to the latest available version + if not specified. + :paramtype server_version: str + :keyword public_network_access: Whether or not public endpoint access is allowed for this mongo + cluster. Known values are: "Enabled" and "Disabled". + :paramtype public_network_access: str or ~azure.mgmt.mongocluster.models.PublicNetworkAccess + :keyword node_group_specs: The list of node group specs in the cluster. + :paramtype node_group_specs: list[~azure.mgmt.mongocluster.models.NodeGroupSpec] + """ + super().__init__(**kwargs) + self.administrator_login = administrator_login + self.administrator_login_password = administrator_login_password + self.server_version = server_version + self.public_network_access = public_network_access + self.node_group_specs = node_group_specs + + +class NodeGroupProperties(_serialization.Model): + """The properties of the node group on a cluster. + + :ivar sku: The resource sku for the node group. This defines the size of CPU and memory that is + provisioned for each node. Example values: 'M30', 'M40'. + :vartype sku: str + :ivar disk_size_gb: The disk storage size for the node group in GB. Example values: 128, 256, + 512, 1024. + :vartype disk_size_gb: int + :ivar enable_ha: Whether high availability is enabled on the node group. + :vartype enable_ha: bool + """ + + _attribute_map = { + "sku": {"key": "sku", "type": "str"}, + "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, + "enable_ha": {"key": "enableHa", "type": "bool"}, + } + + def __init__( + self, + *, + sku: Optional[str] = None, + disk_size_gb: Optional[int] = None, + enable_ha: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword sku: The resource sku for the node group. This defines the size of CPU and memory that + is provisioned for each node. Example values: 'M30', 'M40'. + :paramtype sku: str + :keyword disk_size_gb: The disk storage size for the node group in GB. Example values: 128, + 256, 512, 1024. + :paramtype disk_size_gb: int + :keyword enable_ha: Whether high availability is enabled on the node group. + :paramtype enable_ha: bool + """ + super().__init__(**kwargs) + self.sku = sku + self.disk_size_gb = disk_size_gb + self.enable_ha = enable_ha + + +class NodeGroupSpec(_serialization.Model): + """Specification for a node group. + + :ivar sku: The resource sku for the node group. This defines the size of CPU and memory that is + provisioned for each node. Example values: 'M30', 'M40'. + :vartype sku: str + :ivar disk_size_gb: The disk storage size for the node group in GB. Example values: 128, 256, + 512, 1024. + :vartype disk_size_gb: int + :ivar enable_ha: Whether high availability is enabled on the node group. + :vartype enable_ha: bool + :ivar kind: The node type deployed in the node group. "Shard" + :vartype kind: str or ~azure.mgmt.mongocluster.models.NodeKind + :ivar node_count: The number of nodes in the node group. + :vartype node_count: int + """ + + _attribute_map = { + "sku": {"key": "sku", "type": "str"}, + "disk_size_gb": {"key": "diskSizeGB", "type": "int"}, + "enable_ha": {"key": "enableHa", "type": "bool"}, + "kind": {"key": "kind", "type": "str"}, + "node_count": {"key": "nodeCount", "type": "int"}, + } + + def __init__( + self, + *, + sku: Optional[str] = None, + disk_size_gb: Optional[int] = None, + enable_ha: Optional[bool] = None, + kind: Optional[Union[str, "_models.NodeKind"]] = None, + node_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword sku: The resource sku for the node group. This defines the size of CPU and memory that + is provisioned for each node. Example values: 'M30', 'M40'. + :paramtype sku: str + :keyword disk_size_gb: The disk storage size for the node group in GB. Example values: 128, + 256, 512, 1024. + :paramtype disk_size_gb: int + :keyword enable_ha: Whether high availability is enabled on the node group. + :paramtype enable_ha: bool + :keyword kind: The node type deployed in the node group. "Shard" + :paramtype kind: str or ~azure.mgmt.mongocluster.models.NodeKind + :keyword node_count: The number of nodes in the node group. + :paramtype node_count: int + """ + super().__init__(**kwargs) + self.sku = sku + self.disk_size_gb = disk_size_gb + self.enable_ha = enable_ha + self.kind = kind + self.node_count = node_count + + +class Operation(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.mongocluster.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.mongocluster.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.mongocluster.models.ActionType + """ + + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: + """ + :keyword display: Localized display information for this particular operation. + :paramtype display: ~azure.mgmt.mongocluster.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = None + self.is_data_action = None + self.display = display + self.origin = None + self.action_type = None + + +class OperationDisplay(_serialization.Model): + """Localized display information for this particular operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". + :vartype provider: str + :ivar resource: The localized friendly name of the resource type related to this operation. + E.g. "Virtual Machines" or "Job Schedule Collections". + :vartype resource: str + :ivar operation: The concise, localized friendly name for the operation; suitable for + dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". + :vartype operation: str + :ivar description: The short, localized friendly description of the operation; suitable for + tool tips and detailed views. + :vartype description: str + """ + + _validation = { + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, + } + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(_serialization.Model): + """A list of REST API operations supported by an Azure Resource Provider. It contains an URL link + to get the next set of results. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of operations supported by the resource provider. + :vartype value: list[~azure.mgmt.mongocluster.models.Operation] + :ivar next_link: URL to get the next set of operation list results (if there are any). + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class PrivateEndpoint(_serialization.Model): + """The private endpoint resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The ARM identifier for private endpoint. + :vartype id: str + """ + + _validation = { + "id": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id = None + + +class PrivateEndpointConnection(Resource): + """The private endpoint connection resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + :ivar properties: Resource properties. + :vartype properties: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "PrivateEndpointConnectionProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.PrivateEndpointConnectionProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: Resource properties. + :paramtype properties: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class PrivateEndpointConnectionProperties(_serialization.Model): + """Properties of the private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar group_ids: The group ids for the private endpoint resource. + :vartype group_ids: list[str] + :ivar private_endpoint: The private endpoint resource. + :vartype private_endpoint: ~azure.mgmt.mongocluster.models.PrivateEndpoint + :ivar private_link_service_connection_state: A collection of information about the state of the + connection between service consumer and provider. Required. + :vartype private_link_service_connection_state: + ~azure.mgmt.mongocluster.models.PrivateLinkServiceConnectionState + :ivar provisioning_state: The provisioning state of the private endpoint connection resource. + Known values are: "Succeeded", "Creating", "Deleting", and "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionProvisioningState + """ + + _validation = { + "group_ids": {"readonly": True}, + "private_link_service_connection_state": {"required": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "group_ids": {"key": "groupIds", "type": "[str]"}, + "private_endpoint": {"key": "privateEndpoint", "type": "PrivateEndpoint"}, + "private_link_service_connection_state": { + "key": "privateLinkServiceConnectionState", + "type": "PrivateLinkServiceConnectionState", + }, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + } + + def __init__( + self, + *, + private_link_service_connection_state: "_models.PrivateLinkServiceConnectionState", + private_endpoint: Optional["_models.PrivateEndpoint"] = None, + **kwargs: Any + ) -> None: + """ + :keyword private_endpoint: The private endpoint resource. + :paramtype private_endpoint: ~azure.mgmt.mongocluster.models.PrivateEndpoint + :keyword private_link_service_connection_state: A collection of information about the state of + the connection between service consumer and provider. Required. + :paramtype private_link_service_connection_state: + ~azure.mgmt.mongocluster.models.PrivateLinkServiceConnectionState + """ + super().__init__(**kwargs) + self.group_ids = None + self.private_endpoint = private_endpoint + self.private_link_service_connection_state = private_link_service_connection_state + self.provisioning_state = None + + +class PrivateEndpointConnectionResource(ProxyResource): + """Concrete proxy resource types can be created by aliasing this type using a specific property + type. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "PrivateEndpointConnectionProperties"}, + } + + def __init__( + self, *, properties: Optional["_models.PrivateEndpointConnectionProperties"] = None, **kwargs: Any + ) -> None: + """ + :keyword properties: The resource-specific properties for this resource. + :paramtype properties: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class PrivateEndpointConnectionResourceListResult(_serialization.Model): # pylint: disable=name-too-long + """The response of a PrivateEndpointConnectionResource list operation. + + All required parameters must be populated in order to send to server. + + :ivar value: The PrivateEndpointConnectionResource items on this page. Required. + :vartype value: list[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[PrivateEndpointConnectionResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: List["_models.PrivateEndpointConnectionResource"], + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: The PrivateEndpointConnectionResource items on this page. Required. + :paramtype value: list[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PrivateLinkResource(ProxyResource): + """Concrete proxy resource types can be created by aliasing this type using a specific property + type. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". # pylint: disable=line-too-long + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.mongocluster.models.SystemData + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.mongocluster.models.PrivateLinkResourceProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "PrivateLinkResourceProperties"}, + } + + def __init__(self, *, properties: Optional["_models.PrivateLinkResourceProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: The resource-specific properties for this resource. + :paramtype properties: ~azure.mgmt.mongocluster.models.PrivateLinkResourceProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class PrivateLinkResourceListResult(_serialization.Model): + """The response of a PrivateLinkResource list operation. + + All required parameters must be populated in order to send to server. + + :ivar value: The PrivateLinkResource items on this page. Required. + :vartype value: list[~azure.mgmt.mongocluster.models.PrivateLinkResource] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[PrivateLinkResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: List["_models.PrivateLinkResource"], next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The PrivateLinkResource items on this page. Required. + :paramtype value: list[~azure.mgmt.mongocluster.models.PrivateLinkResource] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PrivateLinkResourceProperties(_serialization.Model): + """Properties of a private link resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + :ivar required_zone_names: The private link resource private link DNS zone name. + :vartype required_zone_names: list[str] + """ + + _validation = { + "group_id": {"readonly": True}, + "required_members": {"readonly": True}, + } + + _attribute_map = { + "group_id": {"key": "groupId", "type": "str"}, + "required_members": {"key": "requiredMembers", "type": "[str]"}, + "required_zone_names": {"key": "requiredZoneNames", "type": "[str]"}, + } + + def __init__(self, *, required_zone_names: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + :keyword required_zone_names: The private link resource private link DNS zone name. + :paramtype required_zone_names: list[str] + """ + super().__init__(**kwargs) + self.group_id = None + self.required_members = None + self.required_zone_names = required_zone_names + + +class PrivateLinkServiceConnectionState(_serialization.Model): + """A collection of information about the state of the connection between service consumer and + provider. + + :ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner + of the service. Known values are: "Pending", "Approved", and "Rejected". + :vartype status: str or ~azure.mgmt.mongocluster.models.PrivateEndpointServiceConnectionStatus + :ivar description: The reason for approval/rejection of the connection. + :vartype description: str + :ivar actions_required: A message indicating if changes on the service provider require any + updates on the consumer. + :vartype actions_required: str + """ + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, + } + + def __init__( + self, + *, + status: Optional[Union[str, "_models.PrivateEndpointServiceConnectionStatus"]] = None, + description: Optional[str] = None, + actions_required: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword status: Indicates whether the connection has been Approved/Rejected/Removed by the + owner of the service. Known values are: "Pending", "Approved", and "Rejected". + :paramtype status: str or + ~azure.mgmt.mongocluster.models.PrivateEndpointServiceConnectionStatus + :keyword description: The reason for approval/rejection of the connection. + :paramtype description: str + :keyword actions_required: A message indicating if changes on the service provider require any + updates on the consumer. + :paramtype actions_required: str + """ + super().__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = actions_required + + +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.mongocluster.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.mongocluster.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.mongocluster.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or ~azure.mgmt.mongocluster.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_mongo_cluster_management_client_enums.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_mongo_cluster_management_client_enums.py new file mode 100644 index 000000000000..90291f962483 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_mongo_cluster_management_client_enums.py @@ -0,0 +1,122 @@ +# 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 enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" + + INTERNAL = "Internal" + + +class CheckNameAvailabilityReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The reason why the given name is not available.""" + + INVALID = "Invalid" + ALREADY_EXISTS = "AlreadyExists" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class CreateMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The mode that the Mongo Cluster is created with.""" + + DEFAULT = "Default" + """Create a new mongo cluster.""" + POINT_IN_TIME_RESTORE = "PointInTimeRestore" + """Create a mongo cluster from a restore point-in-time.""" + + +class MongoClusterStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the Mongo cluster resource.""" + + READY = "Ready" + """The mongo cluster resource is ready for use.""" + PROVISIONING = "Provisioning" + """The mongo cluster resource is being provisioned.""" + UPDATING = "Updating" + """The mongo cluster resource is being updated.""" + STARTING = "Starting" + """The mongo cluster resource is being started.""" + STOPPING = "Stopping" + """The mongo cluster resource is being stopped.""" + STOPPED = "Stopped" + """The mongo cluster resource is stopped.""" + DROPPING = "Dropping" + """The mongo cluster resource is being dropped.""" + + +class NodeKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of the node on the cluster.""" + + SHARD = "Shard" + """The node is a shard kind.""" + + +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is "user,system". + """ + + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" + + +class PrivateEndpointConnectionProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current provisioning state.""" + + SUCCEEDED = "Succeeded" + CREATING = "Creating" + DELETING = "Deleting" + FAILED = "Failed" + + +class PrivateEndpointServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The private endpoint connection status.""" + + PENDING = "Pending" + APPROVED = "Approved" + REJECTED = "Rejected" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state of the last accepted operation.""" + + SUCCEEDED = "Succeeded" + """Resource has been created.""" + FAILED = "Failed" + """Resource creation failed.""" + CANCELED = "Canceled" + """Resource creation was canceled.""" + IN_PROGRESS = "InProgress" + """An operation is in-progress on the resource.""" + UPDATING = "Updating" + """An update operation is in-progress on the resource.""" + DROPPING = "Dropping" + """A drop operation is in-progress on the resource.""" + + +class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Whether or not public endpoint access is allowed for this Mongo cluster. Value is optional and + default value is 'Enabled'. + """ + + ENABLED = "Enabled" + """If set, mongo cluster can be accessed through private and public methods.""" + DISABLED = "Disabled" + """If set, the private endpoints are the exclusive access method.""" diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_patch.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/__init__.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/__init__.py new file mode 100644 index 000000000000..3300f25ba7be --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/__init__.py @@ -0,0 +1,27 @@ +# 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 Operations +from ._mongo_clusters_operations import MongoClustersOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._private_links_operations import PrivateLinksOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Operations", + "MongoClustersOperations", + "FirewallRulesOperations", + "PrivateEndpointConnectionsOperations", + "PrivateLinksOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_firewall_rules_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_firewall_rules_operations.py new file mode 100644 index 000000000000..32d829d9b2df --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_firewall_rules_operations.py @@ -0,0 +1,719 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_mongo_cluster_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # 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_get_request( + resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules/{firewallRuleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "firewallRuleName": _SERIALIZER.url( + "firewall_rule_name", + firewall_rule_name, + "str", + max_length=80, + min_length=1, + pattern=r"^[a-zA-Z0-9][-_.a-zA-Z0-9]*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules/{firewallRuleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "firewallRuleName": _SERIALIZER.url( + "firewall_rule_name", + firewall_rule_name, + "str", + max_length=80, + min_length=1, + pattern=r"^[a-zA-Z0-9][-_.a-zA-Z0-9]*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules/{firewallRuleName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "firewallRuleName": _SERIALIZER.url( + "firewall_rule_name", + firewall_rule_name, + "str", + max_length=80, + min_length=1, + pattern=r"^[a-zA-Z0-9][-_.a-zA-Z0-9]*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class FirewallRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.MongoClusterManagementClient`'s + :attr:`firewall_rules` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_mongo_cluster( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> Iterable["_models.FirewallRule"]: + """List all the firewall rules in a given mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An iterator like instance of either FirewallRule or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FirewallRuleListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_mongo_cluster_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("FirewallRuleListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, **kwargs: Any + ) -> _models.FirewallRule: + """Gets information about a mongo cluster firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :return: FirewallRule or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.FirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.FirewallRule] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("FirewallRule", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: Union[_models.FirewallRule, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.FirewallRule]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.FirewallRule]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "FirewallRule") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("FirewallRule", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("FirewallRule", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: _models.FirewallRule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.mongocluster.models.FirewallRule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + firewall_rule_name: str, + resource: Union[_models.FirewallRule, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :param resource: Resource create parameters. Is either a FirewallRule type or a IO[bytes] type. + Required. + :type resource: ~azure.mgmt.mongocluster.models.FirewallRule or IO[bytes] + :return: An instance of LROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.FirewallRule] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("FirewallRule", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.FirewallRule].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.FirewallRule]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, mongo_cluster_name: str, firewall_rule_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes a mongo cluster firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param firewall_rule_name: The name of the mongo cluster firewall rule. Required. + :type firewall_rule_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + firewall_rule_name=firewall_rule_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_mongo_clusters_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_mongo_clusters_operations.py new file mode 100644 index 000000000000..25755c48827f --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_mongo_clusters_operations.py @@ -0,0 +1,1243 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/checkMongoClusterNameAvailability", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # 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_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/mongoClusters") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # 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_get_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # 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_update_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # 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_delete_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_connection_strings_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/listConnectionStrings", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class MongoClustersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.MongoClusterManagementClient`'s + :attr:`mongo_clusters` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def check_name_availability( + self, + location: str, + body: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Check if mongo cluster name is available for use. + + :param location: The name of the Azure region. Required. + :type location: str + :param body: The CheckAvailability request. Required. + :type body: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, location: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Check if mongo cluster name is available for use. + + :param location: The name of the Azure region. Required. + :type location: str + :param body: The CheckAvailability request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, body: Union[_models.CheckNameAvailabilityRequest, IO[bytes]], **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Check if mongo cluster name is available for use. + + :param location: The name of the Azure region. Required. + :type location: str + :param body: The CheckAvailability request. Is either a CheckNameAvailabilityRequest type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityRequest or IO[bytes] + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameAvailabilityResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CheckNameAvailabilityRequest") + + _request = build_check_name_availability_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.MongoCluster"]: + """List all the mongo clusters in a given subscription. + + :return: An iterator like instance of either MongoCluster or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoClusterListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MongoClusterListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.MongoCluster"]: + """List all the mongo clusters in a given resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either MongoCluster or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoClusterListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("MongoClusterListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any) -> _models.MongoCluster: + """Gets information about a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: MongoCluster or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.MongoCluster + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: Union[_models.MongoCluster, IO[bytes]], + **kwargs: Any + ) -> _models.MongoCluster: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "MongoCluster") + + _request = build_create_or_update_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if response.status_code == 201: + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: _models.MongoCluster, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoCluster]: + """Create or update a mongo cluster. Update overwrites all properties for the resource. To only + modify some of the properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.mongocluster.models.MongoCluster + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoCluster]: + """Create or update a mongo cluster. Update overwrites all properties for the resource. To only + modify some of the properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + resource: Union[_models.MongoCluster, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.MongoCluster]: + """Create or update a mongo cluster. Update overwrites all properties for the resource. To only + modify some of the properties, use PATCH. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param resource: Resource create parameters. Is either a MongoCluster type or a IO[bytes] type. + Required. + :type resource: ~azure.mgmt.mongocluster.models.MongoCluster or IO[bytes] + :return: An instance of LROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoCluster", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.MongoCluster].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.MongoCluster]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: Union[_models.MongoClusterUpdate, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.MongoCluster]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.MongoCluster]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "MongoClusterUpdate") + + _request = build_update_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("MongoCluster", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: _models.MongoClusterUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoCluster]: + """Updates an existing mongo cluster. The request body can contain one to many of the properties + present in the normal mongo cluster definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.mongocluster.models.MongoClusterUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.MongoCluster]: + """Updates an existing mongo cluster. The request body can contain one to many of the properties + present in the normal mongo cluster definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + mongo_cluster_name: str, + properties: Union[_models.MongoClusterUpdate, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.MongoCluster]: + """Updates an existing mongo cluster. The request body can contain one to many of the properties + present in the normal mongo cluster definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param properties: The resource properties to be updated. Is either a MongoClusterUpdate type + or a IO[bytes] type. Required. + :type properties: ~azure.mgmt.mongocluster.models.MongoClusterUpdate or IO[bytes] + :return: An instance of LROPoller that returns either MongoCluster or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.MongoCluster] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MongoCluster] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + properties=properties, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("MongoCluster", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.MongoCluster].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.MongoCluster]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def begin_delete(self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes a mongo cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_connection_strings( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> _models.ListConnectionStringsResult: + """List mongo cluster connection strings. This includes the default connection string using + SCRAM-SHA-256, as well as other connection strings supported by the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: ListConnectionStringsResult or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.ListConnectionStringsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.ListConnectionStringsResult] = kwargs.pop("cls", None) + + _request = build_list_connection_strings_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ListConnectionStringsResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_operations.py new file mode 100644 index 000000000000..ebf049549fbc --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_operations.py @@ -0,0 +1,156 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.DocumentDB/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.MongoClusterManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.mongocluster.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_patch.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/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/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_endpoint_connections_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_endpoint_connections_operations.py new file mode 100644 index 000000000000..15a4bc3c3217 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,726 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_mongo_cluster_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # 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_get_request( + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request( + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.MongoClusterManagementClient`'s + :attr:`private_endpoint_connections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_mongo_cluster( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateEndpointConnectionResource"]: + """List existing private connections. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An iterator like instance of either PrivateEndpointConnectionResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnectionResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_mongo_cluster_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get( + self, resource_group_name: str, mongo_cluster_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionResource: + """Get a specific private connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: PrivateEndpointConnectionResource or the result of cls(response) + :rtype: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateEndpointConnectionResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_initial( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: Union[_models.PrivateEndpointConnectionResource, IO[bytes]], + **kwargs: Any + ) -> Optional[_models.PrivateEndpointConnectionResource]: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.PrivateEndpointConnectionResource]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "PrivateEndpointConnectionResource") + + _request = build_create_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: _models.PrivateEndpointConnectionResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnectionResource]: + """Create a Private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PrivateEndpointConnectionResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnectionResource]: + """Create a Private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either PrivateEndpointConnectionResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + mongo_cluster_name: str, + private_endpoint_connection_name: str, + resource: Union[_models.PrivateEndpointConnectionResource, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnectionResource]: + """Create a Private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param resource: Resource create parameters. Is either a PrivateEndpointConnectionResource type + or a IO[bytes] type. Required. + :type resource: ~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource or IO[bytes] + :return: An instance of LROPoller that returns either PrivateEndpointConnectionResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.mongocluster.models.PrivateEndpointConnectionResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnectionResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + resource=resource, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnectionResource", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.PrivateEndpointConnectionResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PrivateEndpointConnectionResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, mongo_cluster_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> None: + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, mongo_cluster_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Delete the private endpoint connection. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + private_endpoint_connection_name=private_endpoint_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_links_operations.py b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_links_operations.py new file mode 100644 index 000000000000..4ccc10e99e3b --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/operations/_private_links_operations.py @@ -0,0 +1,187 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_mongo_cluster_request( + resource_group_name: str, mongo_cluster_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateLinkResources", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "mongoClusterName": _SERIALIZER.url( + "mongo_cluster_name", + mongo_cluster_name, + "str", + max_length=40, + min_length=3, + pattern=r"^[a-z0-9]+(-[a-z0-9]+)*", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PrivateLinksOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.mongocluster.MongoClusterManagementClient`'s + :attr:`private_links` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_mongo_cluster( + self, resource_group_name: str, mongo_cluster_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateLinkResource"]: + """list private links on the given resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param mongo_cluster_name: The name of the mongo cluster. Required. + :type mongo_cluster_name: str + :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.mongocluster.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping[int, Type[HttpResponseError]] = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_mongo_cluster_request( + resource_group_name=resource_group_name, + mongo_cluster_name=mongo_cluster_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + _request = _convert_request(_request) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/py.typed b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/azure/mgmt/mongocluster/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create.py new file mode 100644 index 000000000000..a59722f1fa26 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create.py @@ -0,0 +1,55 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.begin_create_or_update( + resource_group_name="TestResourceGroup", + mongo_cluster_name="myMongoCluster", + resource={ + "location": "westus2", + "properties": { + "administratorLogin": "mongoAdmin", + "administratorLoginPassword": "password", + "nodeGroupSpecs": [ + {"diskSizeGB": 128, "enableHa": True, "kind": "Shard", "nodeCount": 1, "sku": "M30"} + ], + "serverVersion": "5.0", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_Create.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create_pitr.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create_pitr.py new file mode 100644 index 000000000000..6000e678a3d7 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_create_pitr.py @@ -0,0 +1,54 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_create_pitr.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.begin_create_or_update( + resource_group_name="TestResourceGroup", + mongo_cluster_name="myMongoCluster", + resource={ + "location": "westus2", + "properties": { + "createMode": "PointInTimeRestore", + "restoreParameters": { + "pointInTimeUTC": "2023-01-13T20:07:35Z", + "sourceResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/TestResourceGroup/providers/Microsoft.DocumentDB/mongoClusters/myOtherMongoCluster", + }, + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_CreatePITR.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_delete.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_delete.py new file mode 100644 index 000000000000..87fce782273c --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_delete.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + client.mongo_clusters.begin_delete( + resource_group_name="TestResourceGroup", + mongo_cluster_name="myMongoCluster", + ).result() + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_Delete.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_create.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_create.py new file mode 100644 index 000000000000..f578bff8feb7 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_create.py @@ -0,0 +1,46 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_firewall_rule_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.firewall_rules.begin_create_or_update( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + firewall_rule_name="rule1", + resource={"properties": {"endIpAddress": "255.255.255.255", "startIpAddress": "0.0.0.0"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_FirewallRuleCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_delete.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_delete.py new file mode 100644 index 000000000000..674d2295910b --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_firewall_rule_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + client.firewall_rules.begin_delete( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + firewall_rule_name="rule1", + ).result() + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_FirewallRuleDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_get.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_get.py new file mode 100644 index 000000000000..00e24e7135ea --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_get.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_firewall_rule_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.firewall_rules.get( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + firewall_rule_name="rule1", + ) + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_FirewallRuleGet.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_list.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_list.py new file mode 100644 index 000000000000..7822753c4866 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_firewall_rule_list.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_firewall_rule_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.firewall_rules.list_by_mongo_cluster( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_FirewallRuleList.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_get.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_get.py new file mode 100644 index 000000000000..84e89221475e --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_get.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.get( + resource_group_name="TestResourceGroup", + mongo_cluster_name="myMongoCluster", + ) + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_Get.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list.py new file mode 100644 index 000000000000..9d38aa958f99 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_List.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_by_resource_group.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_by_resource_group.py new file mode 100644 index 000000000000..87cb4c60ed65 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_by_resource_group.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_list_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.list_by_resource_group( + resource_group_name="TestResourceGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_ListByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_connection_strings.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_connection_strings.py new file mode 100644 index 000000000000..bf50e91aadc4 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_list_connection_strings.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_list_connection_strings.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.list_connection_strings( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + ) + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_ListConnectionStrings.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability.py new file mode 100644 index 000000000000..5e7bf8a9989d --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability.py @@ -0,0 +1,44 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_name_availability.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.check_name_availability( + location="westus2", + body={"name": "newmongocluster", "type": "Microsoft.DocumentDB/mongoClusters"}, + ) + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_NameAvailability.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability_already_exists.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability_already_exists.py new file mode 100644 index 000000000000..91addd87d204 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_name_availability_already_exists.py @@ -0,0 +1,44 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_name_availability_already_exists.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.check_name_availability( + location="westus2", + body={"name": "existingmongocluster", "type": "Microsoft.DocumentDB/mongoClusters"}, + ) + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_NameAvailability_AlreadyExists.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_disk_size.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_disk_size.py new file mode 100644 index 000000000000..602a7cf5ee2f --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_disk_size.py @@ -0,0 +1,45 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_patch_disk_size.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.begin_update( + resource_group_name="TestResourceGroup", + mongo_cluster_name="myMongoCluster", + properties={"properties": {"nodeGroupSpecs": [{"diskSizeGB": 256, "kind": "Shard"}]}}, + ).result() + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_PatchDiskSize.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_private_network_access.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_private_network_access.py new file mode 100644 index 000000000000..8019fab769d4 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_patch_private_network_access.py @@ -0,0 +1,45 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_patch_private_network_access.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.begin_update( + resource_group_name="TestResourceGroup", + mongo_cluster_name="myMongoCluster", + properties={"properties": {"publicNetworkAccess": "Disabled"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_PatchPrivateNetworkAccess.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_delete.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_delete.py new file mode 100644 index 000000000000..6690c35d1d14 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_private_endpoint_connection_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + client.private_endpoint_connections.begin_delete( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + private_endpoint_connection_name="pecTest.5d393f64-ef64-46d0-9959-308321c44ac0", + ).result() + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_PrivateEndpointConnectionDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_get.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_get.py new file mode 100644 index 000000000000..f2ddc0c16a29 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_get.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_private_endpoint_connection_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.private_endpoint_connections.get( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + private_endpoint_connection_name="pecTest.5d393f64-ef64-46d0-9959-308321c44ac0", + ) + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_PrivateEndpointConnectionGet.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_list.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_list.py new file mode 100644 index 000000000000..b4434f06ca83 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_list.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_private_endpoint_connection_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.private_endpoint_connections.list_by_mongo_cluster( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_PrivateEndpointConnectionList.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_put.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_put.py new file mode 100644 index 000000000000..54d3f270258f --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_endpoint_connection_put.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_private_endpoint_connection_put.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.private_endpoint_connections.begin_create( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + private_endpoint_connection_name="pecTest", + resource={ + "properties": {"privateLinkServiceConnectionState": {"description": "Auto-Approved", "status": "Approved"}} + }, + ).result() + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_PrivateEndpointConnectionPut.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_link_resource_list.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_link_resource_list.py new file mode 100644 index 000000000000..1c62d4f8e5b3 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_private_link_resource_list.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_private_link_resource_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.private_links.list_by_mongo_cluster( + resource_group_name="TestGroup", + mongo_cluster_name="myMongoCluster", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_PrivateLinkResourceList.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_update.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_update.py new file mode 100644 index 000000000000..aa56829267fd --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/mongo_clusters_update.py @@ -0,0 +1,55 @@ +# 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, IO, Union + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python mongo_clusters_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.mongo_clusters.begin_update( + resource_group_name="TestResourceGroup", + mongo_cluster_name="myMongoCluster", + properties={ + "properties": { + "administratorLogin": "mongoAdmin", + "administratorLoginPassword": "password", + "nodeGroupSpecs": [ + {"diskSizeGB": 256, "enableHa": True, "kind": "Shard", "nodeCount": 1, "sku": "M50"} + ], + "publicNetworkAccess": "Enabled", + "serverVersion": "5.0", + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/MongoClusters_Update.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/operations_list.py b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/operations_list.py new file mode 100644 index 000000000000..76f4c26f55bc --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/generated_samples/operations_list.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.mongocluster import MongoClusterManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-mongocluster +# USAGE + python operations_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = MongoClusterManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.operations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/mongocluster/resource-manager/Microsoft.DocumentDB/preview/2024-03-01-preview/examples/Operations_List.json +if __name__ == "__main__": + main() diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/sdk_packaging.toml b/sdk/mongocluster/azure-mgmt-mongocluster/sdk_packaging.toml new file mode 100644 index 000000000000..dcfb9dcb79e7 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/sdk_packaging.toml @@ -0,0 +1,11 @@ +[packaging] +package_name = "azure-mgmt-mongocluster" +package_nspkg = "azure-mgmt-nspkg" +package_pprint_name = "MyService Management" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" diff --git a/sdk/mongocluster/azure-mgmt-mongocluster/setup.py b/sdk/mongocluster/azure-mgmt-mongocluster/setup.py new file mode 100644 index 000000000000..b272eda73431 --- /dev/null +++ b/sdk/mongocluster/azure-mgmt-mongocluster/setup.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import re +import os.path +from io import open +from setuptools import find_packages, setup + +# Change the PACKAGE_NAME only to change folder and different name +PACKAGE_NAME = "azure-mgmt-mongocluster" +PACKAGE_PPRINT_NAME = "MyService Management" + +# a-b-c => a/b/c +package_folder_path = PACKAGE_NAME.replace("-", "/") +# a-b-c => a.b.c +namespace_name = PACKAGE_NAME.replace("-", ".") + +# Version extraction inspired from 'requests' +with open( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else 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") + +with open("README.md", encoding="utf-8") as f: + readme = f.read() +with open("CHANGELOG.md", encoding="utf-8") as f: + changelog = f.read() + +setup( + name=PACKAGE_NAME, + version=version, + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + 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", + keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product + classifiers=[ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "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.mgmt", + ] + ), + include_package_data=True, + package_data={ + "pytyped": ["py.typed"], + }, + install_requires=[ + "isodate>=0.6.1", + "azure-common>=1.1", + "azure-mgmt-core>=1.3.2", + ], + python_requires=">=3.8", +) diff --git a/sdk/mongocluster/ci.yml b/sdk/mongocluster/ci.yml new file mode 100644 index 000000000000..f8b3d9915e16 --- /dev/null +++ b/sdk/mongocluster/ci.yml @@ -0,0 +1,34 @@ +# DO NOT EDIT THIS FILE +# This file is generated automatically and any changes will be lost. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/mongocluster/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/mongocluster/ + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: mongocluster + TestProxy: true + Artifacts: + - name: azure-mgmt-mongocluster + safeName: azuremgmtmongocluster