From 6bf0f54bc119b0ae966b667faed802b8081385ae Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 26 May 2021 15:22:48 -0700 Subject: [PATCH 01/61] Scaffold out the k8s-config package --- .github/CODEOWNERS | 1 + src/k8s-config/HISTORY.rst | 8 + src/k8s-config/README.rst | 5 + src/k8s-config/azext_k8s_config/__init__.py | 32 + .../azext_k8s_config/_client_factory.py | 14 + src/k8s-config/azext_k8s_config/_help.py | 38 + src/k8s-config/azext_k8s_config/_params.py | 23 + .../azext_k8s_config/_validators.py | 20 + .../azext_k8s_config/azext_metadata.json | 3 + src/k8s-config/azext_k8s_config/commands.py | 22 + src/k8s-config/azext_k8s_config/custom.py | 16 + .../azext_k8s_config/tests/__init__.py | 5 + .../azext_k8s_config/tests/latest/__init__.py | 5 + .../tests/latest/test_k8s-config_scenario.py | 40 + .../vendored_sdks/__init__.py | 19 + .../vendored_sdks/_configuration.py | 71 + .../_source_control_configuration_client.py | 134 ++ .../vendored_sdks/_version.py | 9 + .../vendored_sdks/aio/__init__.py | 10 + .../vendored_sdks/aio/_configuration.py | 67 + .../_source_control_configuration_client.py | 127 ++ .../vendored_sdks/aio/operations/__init__.py | 31 + .../_cluster_extension_type_operations.py | 114 ++ .../_cluster_extension_types_operations.py | 122 ++ .../_extension_type_versions_operations.py | 117 ++ .../aio/operations/_extensions_operations.py | 495 ++++++ ...flux_config_operation_status_operations.py | 118 ++ .../_flux_configurations_operations.py | 491 ++++++ .../_location_extension_types_operations.py | 113 ++ .../_operation_status_operations.py | 204 +++ .../aio/operations/_operations.py | 105 ++ ...ource_control_configurations_operations.py | 420 +++++ .../vendored_sdks/models/__init__.py | 147 ++ .../vendored_sdks/models/_models.py | 1329 +++++++++++++++ .../vendored_sdks/models/_models_py3.py | 1446 +++++++++++++++++ ...urce_control_configuration_client_enums.py | 148 ++ .../vendored_sdks/operations/__init__.py | 31 + .../_cluster_extension_type_operations.py | 119 ++ .../_cluster_extension_types_operations.py | 127 ++ .../_extension_type_versions_operations.py | 122 ++ .../operations/_extensions_operations.py | 505 ++++++ ...flux_config_operation_status_operations.py | 123 ++ .../_flux_configurations_operations.py | 501 ++++++ .../_location_extension_types_operations.py | 118 ++ .../_operation_status_operations.py | 210 +++ .../vendored_sdks/operations/_operations.py | 110 ++ ...ource_control_configurations_operations.py | 429 +++++ src/k8s-config/setup.cfg | 2 + src/k8s-config/setup.py | 60 + 49 files changed, 8526 insertions(+) create mode 100644 src/k8s-config/HISTORY.rst create mode 100644 src/k8s-config/README.rst create mode 100644 src/k8s-config/azext_k8s_config/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/_client_factory.py create mode 100644 src/k8s-config/azext_k8s_config/_help.py create mode 100644 src/k8s-config/azext_k8s_config/_params.py create mode 100644 src/k8s-config/azext_k8s_config/_validators.py create mode 100644 src/k8s-config/azext_k8s_config/azext_metadata.json create mode 100644 src/k8s-config/azext_k8s_config/commands.py create mode 100644 src/k8s-config/azext_k8s_config/custom.py create mode 100644 src/k8s-config/azext_k8s_config/tests/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/_version.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_config_operation_status_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/models/_models.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/models/_models_py3.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_config_operation_status_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/setup.cfg create mode 100644 src/k8s-config/setup.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 63b4a123364..8c3fd203991 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -191,3 +191,4 @@ /src/cloudservice/ @qwordy /src/webpubsub/ @zackliu +/src/azext_k8s-config/ @(env) PS C:\Users\joinnis.REDMOND\github\azure-cli-extensions> azdev extension create k8s-config diff --git a/src/k8s-config/HISTORY.rst b/src/k8s-config/HISTORY.rst new file mode 100644 index 00000000000..8c34bccfff8 --- /dev/null +++ b/src/k8s-config/HISTORY.rst @@ -0,0 +1,8 @@ +.. :changelog: + +Release History +=============== + +0.1.0 +++++++ +* Initial release. \ No newline at end of file diff --git a/src/k8s-config/README.rst b/src/k8s-config/README.rst new file mode 100644 index 00000000000..744151c134d --- /dev/null +++ b/src/k8s-config/README.rst @@ -0,0 +1,5 @@ +Microsoft Azure CLI 'k8s-config' Extension +========================================== + +This package is for the 'k8s-config' extension. +i.e. 'az k8s-config' \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/__init__.py b/src/k8s-config/azext_k8s_config/__init__.py new file mode 100644 index 00000000000..edc0dafcd39 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/__init__.py @@ -0,0 +1,32 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core import AzCommandsLoader + +from azext_k8s_config._help import helps # pylint: disable=unused-import + + +class k8s_configCommandsLoader(AzCommandsLoader): + + def __init__(self, cli_ctx=None): + from azure.cli.core.commands import CliCommandType + from azext_k8s_config._client_factory import cf_k8s_config + k8s_config_custom = CliCommandType( + operations_tmpl='azext_k8s_config.custom#{}', + client_factory=cf_k8s_config) + super(k8s_configCommandsLoader, self).__init__(cli_ctx=cli_ctx, + custom_command_type=k8s_config_custom) + + def load_command_table(self, args): + from azext_k8s_config.commands import load_command_table + load_command_table(self, args) + return self.command_table + + def load_arguments(self, command): + from azext_k8s_config._params import load_arguments + load_arguments(self, command) + + +COMMAND_LOADER_CLS = k8s_configCommandsLoader diff --git a/src/k8s-config/azext_k8s_config/_client_factory.py b/src/k8s-config/azext_k8s_config/_client_factory.py new file mode 100644 index 00000000000..39bf4814422 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/_client_factory.py @@ -0,0 +1,14 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +def cf_k8s_config(cli_ctx, *_): + from azure.cli.core.commands.client_factory import get_mgmt_service_client + from azext_k8s_config.vendored_sdks import SourceControlConfigurationClient + return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient) + + +def cf_k8s_config_fc_operations(cli_ctx, _): + return cf_k8s_config(cli_ctx).flux_configurations diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py new file mode 100644 index 00000000000..19900e3cfd3 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from knack.help_files import helps # pylint: disable=unused-import + + +helps['k8s-config'] = """ + type: group + short-summary: Commands to manage K8s-configs. +""" + +helps['k8s-config create'] = """ + type: command + short-summary: Create a K8s-config. +""" + +helps['k8s-config list'] = """ + type: command + short-summary: List K8s-configs. +""" + +# helps['k8s-config delete'] = """ +# type: command +# short-summary: Delete a K8s-config. +# """ + +# helps['k8s-config show'] = """ +# type: command +# short-summary: Show details of a K8s-config. +# """ + +# helps['k8s-config update'] = """ +# type: command +# short-summary: Update a K8s-config. +# """ diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py new file mode 100644 index 00000000000..9ac9ffb88ce --- /dev/null +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -0,0 +1,23 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=line-too-long + +from knack.arguments import CLIArgumentType + + +def load_arguments(self, _): + + from azure.cli.core.commands.parameters import tags_type + from azure.cli.core.commands.validators import get_default_location_from_resource_group + + k8s-config_name_type = CLIArgumentType(options_list='--k8s-config-name-name', help='Name of the K8s-config.', id_part='name') + + with self.argument_context('k8s-config') as c: + c.argument('tags', tags_type) + c.argument('location', validator=get_default_location_from_resource_group) + c.argument('k8s-config_name', k8s-config_name_type, options_list=['--name', '-n']) + + with self.argument_context('k8s-config list') as c: + c.argument('k8s-config_name', k8s-config_name_type, id_part=None) diff --git a/src/k8s-config/azext_k8s_config/_validators.py b/src/k8s-config/azext_k8s_config/_validators.py new file mode 100644 index 00000000000..821630f5f34 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/_validators.py @@ -0,0 +1,20 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +def example_name_or_id_validator(cmd, namespace): + # Example of a storage account name or ID validator. + # See: https://github.com/Azure/azure-cli/blob/dev/doc/authoring_command_modules/authoring_commands.md#supporting-name-or-id-parameters + from azure.cli.core.commands.client_factory import get_subscription_id + from msrestazure.tools import is_valid_resource_id, resource_id + if namespace.storage_account: + if not is_valid_resource_id(namespace.RESOURCE): + namespace.storage_account = resource_id( + subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, + namespace='Microsoft.Storage', + type='storageAccounts', + name=namespace.storage_account + ) diff --git a/src/k8s-config/azext_k8s_config/azext_metadata.json b/src/k8s-config/azext_k8s_config/azext_metadata.json new file mode 100644 index 00000000000..3695b0d7077 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/azext_metadata.json @@ -0,0 +1,3 @@ +{ + "azext.minCliCoreVersion": "2.15.0" +} \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py new file mode 100644 index 00000000000..f7d3a80c22f --- /dev/null +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -0,0 +1,22 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=line-too-long +from azure.cli.core.commands import CliCommandType +from azext_k8s_config._client_factory import cf_k8s_config_fc_operations + + +def load_command_table(self, _): + k8s_config_fc_sdk = CliCommandType( + operations_tmpl='azext_k8s_config.vendored_sdks.operations#FluxConfigurationsOperations.{}', + client_factory=cf_k8s_config_fc_operations) + + with self.command_group('k8s-config flux', k8s_config_fc_sdk, is_preview=True) as g: + g.custom_command('source create', "flux_create_source", supports_local_cache=True) + g.custom_command('kustomization create', "flux_create_kustomization", supports_local_cache=True) + g.custom_command('delete', 'flux_delete', confirmation=True) + g.command('list', "list") + g.show_command('show', 'get') + diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py new file mode 100644 index 00000000000..47df9f884f3 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/custom.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. +# -------------------------------------------------------------------------------------------- + +from knack.util import CLIError + + +def flux_create_source(client, resource_group_name, cluster_name, name, cluster_type): + raise CLIError('TODO: Implement `k8s-config create`') + +def flux_create_kustomization(client, resource_group_name, cluster_name, name, cluster_type): + raise CLIError('TODO: Implement `k8s-config create`') + +def flux_delete(client, resource_group_name, cluster_name, name, cluster_type): + raise CLIError('TODO: Implement `k8s-config create`') diff --git a/src/k8s-config/azext_k8s_config/tests/__init__.py b/src/k8s-config/azext_k8s_config/tests/__init__.py new file mode 100644 index 00000000000..2dcf9bb68b3 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/__init__.py @@ -0,0 +1,5 @@ +# ----------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ----------------------------------------------------------------------------- \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/tests/latest/__init__.py b/src/k8s-config/azext_k8s_config/tests/latest/__init__.py new file mode 100644 index 00000000000..2dcf9bb68b3 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/__init__.py @@ -0,0 +1,5 @@ +# ----------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ----------------------------------------------------------------------------- \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py new file mode 100644 index 00000000000..bfca0cc60b8 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import os +import unittest + +from azure_devtools.scenario_tests import AllowLargeResponse +from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer) + + +TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + + +class K8s-configScenarioTest(ScenarioTest): + + @ResourceGroupPreparer(name_prefix='cli_test_k8s-config') + def test_k8s-config(self, resource_group): + + self.kwargs.update({ + 'name': 'test1' + }) + + self.cmd('k8s-config create -g {rg} -n {name} --tags foo=doo', checks=[ + self.check('tags.foo', 'doo'), + self.check('name', '{name}') + ]) + self.cmd('k8s-config update -g {rg} -n {name} --tags foo=boo', checks=[ + self.check('tags.foo', 'boo') + ]) + count = len(self.cmd('k8s-config list').get_output_in_json()) + self.cmd('k8s-config show - {rg} -n {name}', checks=[ + self.check('name', '{name}'), + self.check('resourceGroup', '{rg}'), + self.check('tags.foo', 'boo') + ]) + self.cmd('k8s-config delete -g {rg} -n {name}') + final_count = len(self.cmd('k8s-config list').get_output_in_json()) + self.assertTrue(final_count, count - 1) \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py new file mode 100644 index 00000000000..f13062376d7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py @@ -0,0 +1,19 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['SourceControlConfigurationClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py new file mode 100644 index 00000000000..27f67e28de4 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-06-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py new file mode 100644 index 00000000000..e0be530cfde --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py @@ -0,0 +1,134 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import FluxConfigurationsOperations +from .operations import FluxConfigOperationStatusOperations +from .operations import ExtensionsOperations +from .operations import OperationStatusOperations +from .operations import ClusterExtensionTypeOperations +from .operations import ClusterExtensionTypesOperations +from .operations import ExtensionTypeVersionsOperations +from .operations import LocationExtensionTypesOperations +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from . import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar flux_configurations: FluxConfigurationsOperations operations + :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.operations.FluxConfigurationsOperations + :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations + :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.operations.FluxConfigOperationStatusOperations + :ivar extensions: ExtensionsOperations operations + :vartype extensions: azure.mgmt.kubernetesconfiguration.operations.ExtensionsOperations + :ivar operation_status: OperationStatusOperations operations + :vartype operation_status: azure.mgmt.kubernetesconfiguration.operations.OperationStatusOperations + :ivar cluster_extension_type: ClusterExtensionTypeOperations operations + :vartype cluster_extension_type: azure.mgmt.kubernetesconfiguration.operations.ClusterExtensionTypeOperations + :ivar cluster_extension_types: ClusterExtensionTypesOperations operations + :vartype cluster_extension_types: azure.mgmt.kubernetesconfiguration.operations.ClusterExtensionTypesOperations + :ivar extension_type_versions: ExtensionTypeVersionsOperations operations + :vartype extension_type_versions: azure.mgmt.kubernetesconfiguration.operations.ExtensionTypeVersionsOperations + :ivar location_extension_types: LocationExtensionTypesOperations operations + :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.operations.LocationExtensionTypesOperations + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.flux_configurations = FluxConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.flux_config_operation_status = FluxConfigOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.extensions = ExtensionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operation_status = OperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_type = ClusterExtensionTypeOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_types = ClusterExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.extension_type_versions = ExtensionTypeVersionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_extension_types = LocationExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> SourceControlConfigurationClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_version.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_version.py new file mode 100644 index 00000000000..e5754a47ce6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_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/src/k8s-config/azext_k8s_config/vendored_sdks/aio/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/__init__.py new file mode 100644 index 00000000000..ba52c91a7ba --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/__init__.py @@ -0,0 +1,10 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +__all__ = ['SourceControlConfigurationClient'] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py new file mode 100644 index 00000000000..510c9921e82 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-06-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py new file mode 100644 index 00000000000..a60b069516a --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py @@ -0,0 +1,127 @@ +# 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, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import FluxConfigurationsOperations +from .operations import FluxConfigOperationStatusOperations +from .operations import ExtensionsOperations +from .operations import OperationStatusOperations +from .operations import ClusterExtensionTypeOperations +from .operations import ClusterExtensionTypesOperations +from .operations import ExtensionTypeVersionsOperations +from .operations import LocationExtensionTypesOperations +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from .. import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar flux_configurations: FluxConfigurationsOperations operations + :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigurationsOperations + :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations + :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigOperationStatusOperations + :ivar extensions: ExtensionsOperations operations + :vartype extensions: azure.mgmt.kubernetesconfiguration.aio.operations.ExtensionsOperations + :ivar operation_status: OperationStatusOperations operations + :vartype operation_status: azure.mgmt.kubernetesconfiguration.aio.operations.OperationStatusOperations + :ivar cluster_extension_type: ClusterExtensionTypeOperations operations + :vartype cluster_extension_type: azure.mgmt.kubernetesconfiguration.aio.operations.ClusterExtensionTypeOperations + :ivar cluster_extension_types: ClusterExtensionTypesOperations operations + :vartype cluster_extension_types: azure.mgmt.kubernetesconfiguration.aio.operations.ClusterExtensionTypesOperations + :ivar extension_type_versions: ExtensionTypeVersionsOperations operations + :vartype extension_type_versions: azure.mgmt.kubernetesconfiguration.aio.operations.ExtensionTypeVersionsOperations + :ivar location_extension_types: LocationExtensionTypesOperations operations + :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.aio.operations.LocationExtensionTypesOperations + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.aio.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.aio.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :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: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.flux_configurations = FluxConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.flux_config_operation_status = FluxConfigOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.extensions = ExtensionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operation_status = OperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_type = ClusterExtensionTypeOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_types = ClusterExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.extension_type_versions = ExtensionTypeVersionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_extension_types = LocationExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "SourceControlConfigurationClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py new file mode 100644 index 00000000000..84aa36f0694 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py @@ -0,0 +1,31 @@ +# 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 ._flux_configurations_operations import FluxConfigurationsOperations +from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations +from ._extensions_operations import ExtensionsOperations +from ._operation_status_operations import OperationStatusOperations +from ._cluster_extension_type_operations import ClusterExtensionTypeOperations +from ._cluster_extension_types_operations import ClusterExtensionTypesOperations +from ._extension_type_versions_operations import ExtensionTypeVersionsOperations +from ._location_extension_types_operations import LocationExtensionTypesOperations +from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations + +__all__ = [ + 'FluxConfigurationsOperations', + 'FluxConfigOperationStatusOperations', + 'ExtensionsOperations', + 'OperationStatusOperations', + 'ClusterExtensionTypeOperations', + 'ClusterExtensionTypesOperations', + 'ExtensionTypeVersionsOperations', + 'LocationExtensionTypesOperations', + 'SourceControlConfigurationsOperations', + 'Operations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py new file mode 100644 index 00000000000..f3a0857d94b --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ClusterExtensionTypeOperations: + """ClusterExtensionTypeOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_type: Union[str, "_models.Enum9"], + cluster_name: str, + extension_type_name: str, + **kwargs: Any + ) -> "_models.ExtensionType": + """Get Extension Type details. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_type: The Kubernetes cluster resource name - either managedClusters (for AKS + clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum9 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_type_name: Extension type name. + :type extension_type_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionType, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.ExtensionType + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionType"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterType': self._serialize.url("cluster_type", cluster_type, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionTypeName': self._serialize.url("extension_type_name", extension_type_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionType', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterType}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensionTypes/{extensionTypeName}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py new file mode 100644 index 00000000000..126adc7356b --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.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 typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ClusterExtensionTypesOperations: + """ClusterExtensionTypesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ExtensionTypeList"]: + """Get Extension Types. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionTypeList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/connectedClusters/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensionTypes'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py new file mode 100644 index 00000000000..f89b757ee2a --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py @@ -0,0 +1,117 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ExtensionTypeVersionsOperations: + """ExtensionTypeVersionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location: str, + extension_type_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ExtensionVersionList"]: + """List available versions for an Extension Type. + + :param location: extension location. + :type location: str + :param extension_type_name: Extension type name. + :type extension_type_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionVersionList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionVersionList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'location': self._serialize.url("location", location, 'str'), + 'extensionTypeName': self._serialize.url("extension_type_name", extension_type_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionVersionList', pipeline_response) + list_of_elem = deserialized.versions + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KubernetesConfiguration/locations/{location}/extensionTypes/{extensionTypeName}/versions'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py new file mode 100644 index 00000000000..a3de9bbcd00 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py @@ -0,0 +1,495 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ExtensionsOperations: + """ExtensionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def _create_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_name: str, + extension: "_models.Extension", + **kwargs: Any + ) -> "_models.Extension": + cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(extension, 'Extension') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('Extension', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Extension', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + async def begin_create( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_name: str, + extension: "_models.Extension", + **kwargs: Any + ) -> AsyncLROPoller["_models.Extension"]: + """Create a new Kubernetes Cluster Extension. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param extension: Properties necessary to Create an Extension. + :type extension: ~azure.mgmt.kubernetesconfiguration.models.Extension + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Extension or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.kubernetesconfiguration.models.Extension] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + extension_name=extension_name, + extension=extension, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Extension', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_name: str, + **kwargs: Any + ) -> "_models.Extension": + """Gets Kubernetes Cluster Extension. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Extension, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.Extension + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Extension', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_name: str, + force_delete: Optional[bool] = None, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + if force_delete is not None: + query_parameters['forceDelete'] = self._serialize.query("force_delete", force_delete, 'bool') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_name: str, + force_delete: Optional[bool] = None, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Delete a Kubernetes Cluster Extension. This will cause the Agent to Uninstall the extension + from the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param force_delete: Delete the extension resource in Azure - not the normal asynchronous + delete. + :type force_delete: bool + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + extension_name=extension_name, + force_delete=force_delete, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ExtensionsList"]: + """List all Extensions in the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionsList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionsList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionsList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionsList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_config_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_config_operation_status_operations.py new file mode 100644 index 00000000000..b8fd3066fea --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_config_operation_status_operations.py @@ -0,0 +1,118 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class FluxConfigOperationStatusOperations: + """FluxConfigOperationStatusOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + flux_configuration_name: str, + operation_id: str, + **kwargs: Any + ) -> "_models.OperationStatusResult": + """Get Async Operation status. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :param operation_id: operation Id. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationStatusResult, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationStatusResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}/operations/{operationId}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py new file mode 100644 index 00000000000..1a33042d6b8 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py @@ -0,0 +1,491 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class FluxConfigurationsOperations: + """FluxConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + flux_configuration_name: str, + **kwargs: Any + ) -> "_models.FluxConfiguration": + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FluxConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FluxConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + async def _create_or_update_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + flux_configuration_name: str, + flux_configuration: "_models.FluxConfiguration", + **kwargs: Any + ) -> "_models.FluxConfiguration": + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(flux_configuration, 'FluxConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FluxConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + async def begin_create_or_update( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + flux_configuration_name: str, + flux_configuration: "_models.FluxConfiguration", + **kwargs: Any + ) -> AsyncLROPoller["_models.FluxConfiguration"]: + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :param flux_configuration: Properties necessary to Create a FluxConfiguration. + :type flux_configuration: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FluxConfiguration or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + flux_configuration_name=flux_configuration_name, + flux_configuration=flux_configuration, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FluxConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + flux_configuration_name: str, + force_delete: Optional[bool] = None, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + if force_delete is not None: + query_parameters['forceDelete'] = self._serialize.query("force_delete", force_delete, 'bool') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + flux_configuration_name: str, + force_delete: Optional[bool] = None, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :param force_delete: Delete the extension resource in Azure - not the normal asynchronous + delete. + :type force_delete: bool + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + flux_configuration_name=flux_configuration_name, + force_delete=force_delete, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.FluxConfigurationsList"]: + """List all Flux Configurations. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FluxConfigurationsList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.FluxConfigurationsList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfigurationsList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('FluxConfigurationsList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py new file mode 100644 index 00000000000..ba8ecf56a96 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py @@ -0,0 +1,113 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class LocationExtensionTypesOperations: + """LocationExtensionTypesOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location: str, + **kwargs: Any + ) -> AsyncIterable["_models.ExtensionTypeList"]: + """List all Extension Types. + + :param location: extension location. + :type location: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'location': self._serialize.url("location", location, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionTypeList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KubernetesConfiguration/locations/{location}/extensionTypes'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py new file mode 100644 index 00000000000..6cb43e77638 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py @@ -0,0 +1,204 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class OperationStatusOperations: + """OperationStatusOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.OperationStatusList"]: + """List Async Operations, currently in progress, in a cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either OperationStatusList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.OperationStatusList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('OperationStatusList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_name: str, + operation_id: str, + **kwargs: Any + ) -> "_models.OperationStatusResult": + """Get Async Operation status. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param operation_id: operation Id. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationStatusResult, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationStatusResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}/operations/{operationId}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py new file mode 100644 index 00000000000..3f6d205b105 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py @@ -0,0 +1,105 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ResourceProviderOperationList"]: + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..46e38a3d502 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py @@ -0,0 +1,420 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations: + """SourceControlConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def create_or_update( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + source_control_configuration: "_models.SourceControlConfiguration", + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.SourceControlConfigurationList"]: + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py new file mode 100644 index 00000000000..2d10e26a8b0 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py @@ -0,0 +1,147 @@ +# 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. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import ClusterScopeSettings + from ._models_py3 import ComplianceStatus + from ._models_py3 import ErrorAdditionalInfo + from ._models_py3 import ErrorDetail + from ._models_py3 import ErrorResponse + from ._models_py3 import Extension + from ._models_py3 import ExtensionStatus + from ._models_py3 import ExtensionType + from ._models_py3 import ExtensionTypeList + from ._models_py3 import ExtensionVersionList + from ._models_py3 import ExtensionVersionListVersionsItem + from ._models_py3 import ExtensionsList + from ._models_py3 import FluxConfiguration + from ._models_py3 import FluxConfigurationsList + from ._models_py3 import GitRepositoryDefinition + from ._models_py3 import HelmOperatorProperties + from ._models_py3 import Identity + from ._models_py3 import KustomizationDefinition + from ._models_py3 import OperationStatusList + from ._models_py3 import OperationStatusResult + from ._models_py3 import ProxyResource + from ._models_py3 import RepositoryRefDefinition + from ._models_py3 import Resource + from ._models_py3 import ResourceProviderOperation + from ._models_py3 import ResourceProviderOperationDisplay + from ._models_py3 import ResourceProviderOperationList + from ._models_py3 import Scope + from ._models_py3 import ScopeCluster + from ._models_py3 import ScopeNamespace + from ._models_py3 import SourceControlConfiguration + from ._models_py3 import SourceControlConfigurationList + from ._models_py3 import SupportedScopes + from ._models_py3 import SystemData +except (SyntaxError, ImportError): + from ._models import ClusterScopeSettings # type: ignore + from ._models import ComplianceStatus # type: ignore + from ._models import ErrorAdditionalInfo # type: ignore + from ._models import ErrorDetail # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import Extension # type: ignore + from ._models import ExtensionStatus # type: ignore + from ._models import ExtensionType # type: ignore + from ._models import ExtensionTypeList # type: ignore + from ._models import ExtensionVersionList # type: ignore + from ._models import ExtensionVersionListVersionsItem # type: ignore + from ._models import ExtensionsList # type: ignore + from ._models import FluxConfiguration # type: ignore + from ._models import FluxConfigurationsList # type: ignore + from ._models import GitRepositoryDefinition # type: ignore + from ._models import HelmOperatorProperties # type: ignore + from ._models import Identity # type: ignore + from ._models import KustomizationDefinition # type: ignore + from ._models import OperationStatusList # type: ignore + from ._models import OperationStatusResult # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import RepositoryRefDefinition # type: ignore + from ._models import Resource # type: ignore + from ._models import ResourceProviderOperation # type: ignore + from ._models import ResourceProviderOperationDisplay # type: ignore + from ._models import ResourceProviderOperationList # type: ignore + from ._models import Scope # type: ignore + from ._models import ScopeCluster # type: ignore + from ._models import ScopeNamespace # type: ignore + from ._models import SourceControlConfiguration # type: ignore + from ._models import SourceControlConfigurationList # type: ignore + from ._models import SupportedScopes # type: ignore + from ._models import SystemData # type: ignore + +from ._source_control_configuration_client_enums import ( + ClusterTypes, + ComplianceStateType, + CreatedByType, + Enum0, + Enum1, + Enum9, + KustomizationValidationType, + LevelType, + MessageLevelType, + OperatorScopeType, + OperatorType, + ProvisioningState, + ProvisioningStateType, + ScopeType, + SourceKindType, + SyncStateType, +) + +__all__ = [ + 'ClusterScopeSettings', + 'ComplianceStatus', + 'ErrorAdditionalInfo', + 'ErrorDetail', + 'ErrorResponse', + 'Extension', + 'ExtensionStatus', + 'ExtensionType', + 'ExtensionTypeList', + 'ExtensionVersionList', + 'ExtensionVersionListVersionsItem', + 'ExtensionsList', + 'FluxConfiguration', + 'FluxConfigurationsList', + 'GitRepositoryDefinition', + 'HelmOperatorProperties', + 'Identity', + 'KustomizationDefinition', + 'OperationStatusList', + 'OperationStatusResult', + 'ProxyResource', + 'RepositoryRefDefinition', + 'Resource', + 'ResourceProviderOperation', + 'ResourceProviderOperationDisplay', + 'ResourceProviderOperationList', + 'Scope', + 'ScopeCluster', + 'ScopeNamespace', + 'SourceControlConfiguration', + 'SourceControlConfigurationList', + 'SupportedScopes', + 'SystemData', + 'ClusterTypes', + 'ComplianceStateType', + 'CreatedByType', + 'Enum0', + 'Enum1', + 'Enum9', + 'KustomizationValidationType', + 'LevelType', + 'MessageLevelType', + 'OperatorScopeType', + 'OperatorType', + 'ProvisioningState', + 'ProvisioningStateType', + 'ScopeType', + 'SourceKindType', + 'SyncStateType', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models.py new file mode 100644 index 00000000000..cb9cf66312e --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models.py @@ -0,0 +1,1329 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class Resource(msrest.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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class 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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class ClusterScopeSettings(ProxyResource): + """Extension scope settings. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + :param allow_multiple_instances: Describes if multiple instances of the extension are allowed. + :type allow_multiple_instances: bool + :param default_release_namespace: Default extension release namespace. + :type default_release_namespace: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'allow_multiple_instances': {'key': 'properties.allowMultipleInstances', 'type': 'bool'}, + 'default_release_namespace': {'key': 'properties.defaultReleaseNamespace', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ClusterScopeSettings, self).__init__(**kwargs) + self.allow_multiple_instances = kwargs.get('allow_multiple_instances', None) + self.default_release_namespace = kwargs.get('default_release_namespace', None) + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = kwargs.get('last_config_applied', None) + self.message = kwargs.get('message', None) + self.message_level = kwargs.get('message_level', None) + + +class ErrorAdditionalInfo(msrest.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: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(msrest.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.kubernetesconfiguration.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.kubernetesconfiguration.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 + ): + super(ErrorDetail, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(msrest.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.). + + :param error: The error object. + :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + """ + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = kwargs.get('error', None) + + +class Extension(ProxyResource): + """The Extension object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + :param identity: Identity of the Extension resource. + :type identity: ~azure.mgmt.kubernetesconfiguration.models.Identity + :ivar system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :param extension_type: Type of the Extension, of which this resource is an instance of. It + must be one of the Extension Types registered with Microsoft.KubernetesConfiguration by the + Extension publisher. + :type extension_type: str + :param auto_upgrade_minor_version: Flag to note if this extension participates in auto upgrade + of minor version, or not. + :type auto_upgrade_minor_version: bool + :param release_train: ReleaseTrain this extension participates in for auto-upgrade (e.g. + Stable, Preview, etc.) - only if autoUpgradeMinorVersion is 'true'. + :type release_train: str + :param version: Version of the extension for this extension, if it is 'pinned' to a specific + version. autoUpgradeMinorVersion must be 'false'. + :type version: str + :param scope: Scope at which the extension is installed. + :type scope: ~azure.mgmt.kubernetesconfiguration.models.Scope + :param configuration_settings: Configuration settings, as name-value pairs for configuring this + extension. + :type configuration_settings: dict[str, str] + :param configuration_protected_settings: Configuration settings that are sensitive, as + name-value pairs for configuring this extension. + :type configuration_protected_settings: dict[str, str] + :ivar provisioning_state: Status of installation of this extension. Possible values include: + "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState + :param statuses: Status from this extension. + :type statuses: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionStatus] + :ivar error_info: Error information from the Agent - e.g. errors during installation. + :vartype error_info: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :ivar custom_location_settings: Custom Location settings properties. + :vartype custom_location_settings: dict[str, str] + :ivar package_uri: Uri of the Helm package. + :vartype package_uri: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'error_info': {'readonly': True}, + 'custom_location_settings': {'readonly': True}, + 'package_uri': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'identity': {'key': 'identity', 'type': 'Identity'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'extension_type': {'key': 'properties.extensionType', 'type': 'str'}, + 'auto_upgrade_minor_version': {'key': 'properties.autoUpgradeMinorVersion', 'type': 'bool'}, + 'release_train': {'key': 'properties.releaseTrain', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'scope': {'key': 'properties.scope', 'type': 'Scope'}, + 'configuration_settings': {'key': 'properties.configurationSettings', 'type': '{str}'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'statuses': {'key': 'properties.statuses', 'type': '[ExtensionStatus]'}, + 'error_info': {'key': 'properties.errorInfo', 'type': 'ErrorDetail'}, + 'custom_location_settings': {'key': 'properties.customLocationSettings', 'type': '{str}'}, + 'package_uri': {'key': 'properties.packageUri', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Extension, self).__init__(**kwargs) + self.identity = kwargs.get('identity', None) + self.system_data = None + self.extension_type = kwargs.get('extension_type', None) + self.auto_upgrade_minor_version = kwargs.get('auto_upgrade_minor_version', True) + self.release_train = kwargs.get('release_train', "Stable") + self.version = kwargs.get('version', None) + self.scope = kwargs.get('scope', None) + self.configuration_settings = kwargs.get('configuration_settings', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.provisioning_state = None + self.statuses = kwargs.get('statuses', None) + self.error_info = None + self.custom_location_settings = None + self.package_uri = None + + +class ExtensionsList(msrest.serialization.Model): + """Result of the request to list Extensions. It contains a list of Extension objects and a 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 Extensions within a Kubernetes cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.Extension] + :ivar next_link: URL to get the next set of extension objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Extension]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionsList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ExtensionStatus(msrest.serialization.Model): + """Status from the extension. + + :param code: Status code provided by the Extension. + :type code: str + :param display_status: Short description of status of the extension. + :type display_status: str + :param level: Level of the status. Possible values include: "Error", "Warning", "Information". + Default value: "Information". + :type level: str or ~azure.mgmt.kubernetesconfiguration.models.LevelType + :param message: Detailed message of the status from the Extension. + :type message: str + :param time: DateLiteral (per ISO8601) noting the time of installation status. + :type time: str + """ + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'display_status': {'key': 'displayStatus', 'type': 'str'}, + 'level': {'key': 'level', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'time': {'key': 'time', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionStatus, self).__init__(**kwargs) + self.code = kwargs.get('code', None) + self.display_status = kwargs.get('display_status', None) + self.level = kwargs.get('level', "Information") + self.message = kwargs.get('message', None) + self.time = kwargs.get('time', None) + + +class ExtensionType(msrest.serialization.Model): + """Represents an Extension Type. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :ivar release_trains: Extension release train: preview or stable. + :vartype release_trains: list[str] + :ivar cluster_types: Cluster types. Possible values include: "connectedClusters", + "managedClusters". + :vartype cluster_types: str or ~azure.mgmt.kubernetesconfiguration.models.ClusterTypes + :ivar supported_scopes: Extension scopes. + :vartype supported_scopes: ~azure.mgmt.kubernetesconfiguration.models.SupportedScopes + """ + + _validation = { + 'system_data': {'readonly': True}, + 'release_trains': {'readonly': True}, + 'cluster_types': {'readonly': True}, + 'supported_scopes': {'readonly': True}, + } + + _attribute_map = { + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'release_trains': {'key': 'properties.releaseTrains', 'type': '[str]'}, + 'cluster_types': {'key': 'properties.clusterTypes', 'type': 'str'}, + 'supported_scopes': {'key': 'properties.supportedScopes', 'type': 'SupportedScopes'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionType, self).__init__(**kwargs) + self.system_data = None + self.release_trains = None + self.cluster_types = None + self.supported_scopes = None + + +class ExtensionTypeList(msrest.serialization.Model): + """List Extension Types. + + :param value: The list of Extension Types. + :type value: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionType] + :param next_link: The link to fetch the next page of Extension Types. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ExtensionType]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionTypeList, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class ExtensionVersionList(msrest.serialization.Model): + """List versions for an Extension. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param versions: Versions available for this Extension Type. + :type versions: + list[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionListVersionsItem] + :param next_link: The link to fetch the next page of Extension Types. + :type next_link: str + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + """ + + _validation = { + 'system_data': {'readonly': True}, + } + + _attribute_map = { + 'versions': {'key': 'versions', 'type': '[ExtensionVersionListVersionsItem]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionVersionList, self).__init__(**kwargs) + self.versions = kwargs.get('versions', None) + self.next_link = kwargs.get('next_link', None) + self.system_data = None + + +class ExtensionVersionListVersionsItem(msrest.serialization.Model): + """ExtensionVersionListVersionsItem. + + :param release_train: The release train for this Extension Type. + :type release_train: str + :param versions: Versions available for this Extension Type and release train. + :type versions: list[str] + """ + + _attribute_map = { + 'release_train': {'key': 'releaseTrain', 'type': 'str'}, + 'versions': {'key': 'versions', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionVersionListVersionsItem, self).__init__(**kwargs) + self.release_train = kwargs.get('release_train', None) + self.versions = kwargs.get('versions', None) + + +class FluxConfiguration(ProxyResource): + """The Flux Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :param scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type scope: str or ~azure.mgmt.kubernetesconfiguration.models.ScopeType + :param namespace: The namespace to which this configuration is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type namespace: str + :param source_kind: Source Kind to pull the configuration data from. Possible values include: + "GitRepository". + :type source_kind: str or ~azure.mgmt.kubernetesconfiguration.models.SourceKindType + :param suspend: Whether this configuration should suspend its reconciliation of its + kustomizations and sources. + :type suspend: bool + :param git_repository: Parameters to reconcile to the GitRepository source kind type. + :type git_repository: ~azure.mgmt.kubernetesconfiguration.models.GitRepositoryDefinition + :param kustomizations: Array of kustomizations used to reconcile the artifact pulled by the + source type on the cluster. + :type kustomizations: list[~azure.mgmt.kubernetesconfiguration.models.KustomizationDefinition] + :param configuration_protected_settings: Key-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :ivar statuses: Statuses of the Flux Kubernetes resources created by the fluxConfiguration or + created by the managed objects provisioned by the fluxConfiguration. + :vartype statuses: list[dict[str, any]] + :ivar repository_public_key: Public Key associated with this fluxConfiguration (either + generated within the cluster or provided by the user). + :vartype repository_public_key: str + :ivar last_synced_time: Datetime the fluxConfiguration has been synced with the Azure control + plane. + :vartype last_synced_time: str + :ivar last_synced_commit: Branch and SHA of the last source commit synced with the cluster. + :vartype last_synced_commit: str + :ivar last_config_applied_time: Datetime the fluxConfiguration was last applied. + :vartype last_config_applied_time: str + :ivar sync_state: Combined status of the Flux Kubernetes resources created by the + fluxConfiguration or created by the managed objects. Possible values include: "compliant", + "non-compliant", "syncing". Default value: "syncing". + :vartype sync_state: str or ~azure.mgmt.kubernetesconfiguration.models.SyncStateType + :ivar provisioning_state: Status of the creation of the fluxConfiguration. Possible values + include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState + :ivar message: Error message returned to the user in the case of provisioning failure. + :vartype message: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'statuses': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'last_synced_time': {'readonly': True}, + 'last_synced_commit': {'readonly': True}, + 'last_config_applied_time': {'readonly': True}, + 'sync_state': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'message': {'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'}, + 'scope': {'key': 'properties.scope', 'type': 'str'}, + 'namespace': {'key': 'properties.namespace', 'type': 'str'}, + 'source_kind': {'key': 'properties.sourceKind', 'type': 'str'}, + 'suspend': {'key': 'properties.suspend', 'type': 'bool'}, + 'git_repository': {'key': 'properties.gitRepository', 'type': 'GitRepositoryDefinition'}, + 'kustomizations': {'key': 'properties.kustomizations', 'type': '[KustomizationDefinition]'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'statuses': {'key': 'properties.statuses', 'type': '[{object}]'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'last_synced_time': {'key': 'properties.lastSyncedTime', 'type': 'str'}, + 'last_synced_commit': {'key': 'properties.lastSyncedCommit', 'type': 'str'}, + 'last_config_applied_time': {'key': 'properties.lastConfigAppliedTime', 'type': 'str'}, + 'sync_state': {'key': 'properties.syncState', 'type': 'str'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'message': {'key': 'properties.message', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FluxConfiguration, self).__init__(**kwargs) + self.system_data = None + self.scope = kwargs.get('scope', "cluster") + self.namespace = kwargs.get('namespace', "default") + self.source_kind = kwargs.get('source_kind', None) + self.suspend = kwargs.get('suspend', False) + self.git_repository = kwargs.get('git_repository', None) + self.kustomizations = kwargs.get('kustomizations', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.statuses = None + self.repository_public_key = None + self.last_synced_time = None + self.last_synced_commit = None + self.last_config_applied_time = None + self.sync_state = None + self.provisioning_state = None + self.message = None + + +class FluxConfigurationsList(msrest.serialization.Model): + """Result of the request to list Flux Configurations. It contains a list of FluxConfiguration objects and a 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 Flux Configurations within a Kubernetes cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FluxConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FluxConfigurationsList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class GitRepositoryDefinition(msrest.serialization.Model): + """Parameters to reconcile to the GitRepository source kind type. + + :param url: The URL to sync for the flux configuration git repository. + :type url: str + :param timeout: The maximum time to attempt to reconcile the cluster git repository source with + the remote. + :type timeout: str + :param sync_interval: The interval at which to re-reconcile the cluster git repository source + with the remote. + :type sync_interval: str + :param repository_ref: The source reference for the GitRepository object. + :type repository_ref: ~azure.mgmt.kubernetesconfiguration.models.RepositoryRefDefinition + :param ssh_known_hosts: Base64-encoded known_hosts value containing public SSH keys required to + access private git repositories over SSH. + :type ssh_known_hosts: str + :param https_user: HTTPS username used to access private git repositories over HTTPS. + :type https_user: str + :param auth_ref_override: Name of a local secret on the Kubernetes cluster to use as the + authentication secret rather than the managed or user-provided configuration secrets. + :type auth_ref_override: str + """ + + _attribute_map = { + 'url': {'key': 'url', 'type': 'str'}, + 'timeout': {'key': 'timeout', 'type': 'str'}, + 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, + 'repository_ref': {'key': 'repositoryRef', 'type': 'RepositoryRefDefinition'}, + 'ssh_known_hosts': {'key': 'sshKnownHosts', 'type': 'str'}, + 'https_user': {'key': 'httpsUser', 'type': 'str'}, + 'auth_ref_override': {'key': 'authRefOverride', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(GitRepositoryDefinition, self).__init__(**kwargs) + self.url = kwargs.get('url', None) + self.timeout = kwargs.get('timeout', None) + self.sync_interval = kwargs.get('sync_interval', None) + self.repository_ref = kwargs.get('repository_ref', None) + self.ssh_known_hosts = kwargs.get('ssh_known_hosts', None) + self.https_user = kwargs.get('https_user', None) + self.auth_ref_override = kwargs.get('auth_ref_override', None) + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = kwargs.get('chart_version', None) + self.chart_values = kwargs.get('chart_values', None) + + +class Identity(msrest.serialization.Model): + """Identity for the resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of resource identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of resource. + :vartype tenant_id: str + :ivar type: The identity type. Default value: "SystemAssigned". + :vartype type: str + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + 'type': {'constant': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + type = "SystemAssigned" + + def __init__( + self, + **kwargs + ): + super(Identity, self).__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + + +class KustomizationDefinition(msrest.serialization.Model): + """KustomizationDefinition. + + :param name: The name of the Kustomization object to create on the cluster. + :type name: str + :param path: The path in the source reference to reconcile on the cluster. + :type path: str + :param depends_on: Specifies other Kustomizations that this Kustomization depends on. This + Kustomization will not reconcile until all dependencies have completed their reconciliation. + :type depends_on: list[str] + :param timeout: The maximum time to attempt to reconcile the Kustomization on the cluster. + :type timeout: str + :param sync_interval: The interval at which to re-reconcile the Kustomization on the cluster. + :type sync_interval: str + :param retry_interval: The interval at which to re-reconcile the Kustomization on the cluster + in the event of failure on reconciliation. + :type retry_interval: str + :param prune: Enable/disable garbage collections of Kubernetes objects created by this + Kustomization. + :type prune: bool + :param validation: Specify whether to validate the Kubernetes objects referenced in the + Kustomization before applying them to the cluster. Possible values include: "none", "client", + "server". Default value: "none". + :type validation: str or ~azure.mgmt.kubernetesconfiguration.models.KustomizationValidationType + :param force: Enable/disable re-creating Kubernetes resources on the cluster when patching + fails due to an immutable field change. + :type force: bool + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'path': {'key': 'path', 'type': 'str'}, + 'depends_on': {'key': 'dependsOn', 'type': '[str]'}, + 'timeout': {'key': 'timeout', 'type': 'str'}, + 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, + 'retry_interval': {'key': 'retryInterval', 'type': 'str'}, + 'prune': {'key': 'prune', 'type': 'bool'}, + 'validation': {'key': 'validation', 'type': 'str'}, + 'force': {'key': 'force', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(KustomizationDefinition, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.path = kwargs.get('path', "") + self.depends_on = kwargs.get('depends_on', None) + self.timeout = kwargs.get('timeout', None) + self.sync_interval = kwargs.get('sync_interval', None) + self.retry_interval = kwargs.get('retry_interval', None) + self.prune = kwargs.get('prune', None) + self.validation = kwargs.get('validation', "none") + self.force = kwargs.get('force', None) + + +class OperationStatusList(msrest.serialization.Model): + """The async operations in progress, in the cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of async operations in progress, in the cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult] + :ivar next_link: URL to get the next set of Operation Result objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[OperationStatusResult]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationStatusList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class OperationStatusResult(msrest.serialization.Model): + """The current status of an async operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param id: Fully qualified ID for the async operation. + :type id: str + :param name: Name of the async operation. + :type name: str + :param status: Required. Operation status. + :type status: str + :param properties: Additional information, if available. + :type properties: dict[str, str] + :ivar error: If present, details of the operation error. + :vartype error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + """ + + _validation = { + 'status': {'required': True}, + 'error': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'status': {'key': 'status', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{str}'}, + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationStatusResult, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + self.name = kwargs.get('name', None) + self.status = kwargs['status'] + self.properties = kwargs.get('properties', None) + self.error = None + + +class RepositoryRefDefinition(msrest.serialization.Model): + """The source reference for the GitRepository object. + + :param branch: The git repository branch name to checkout. + :type branch: str + :param tag: The git repository tag name to checkout. This takes precedence over branch. + :type tag: str + :param semver: The semver range used to match against git repository tags. This takes + precedence over tag. + :type semver: str + :param commit: The commit SHA to checkout. This value must be combined with the branch name to + be valid. This takes precedence over semver. + :type commit: str + """ + + _attribute_map = { + 'branch': {'key': 'branch', 'type': 'str'}, + 'tag': {'key': 'tag', 'type': 'str'}, + 'semver': {'key': 'semver', 'type': 'str'}, + 'commit': {'key': 'commit', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RepositoryRefDefinition, self).__init__(**kwargs) + self.branch = kwargs.get('branch', None) + self.tag = kwargs.get('tag', None) + self.semver = kwargs.get('semver', None) + self.commit = kwargs.get('commit', None) + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: ~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationDisplay + :param origin: The intended executor of the operation;governs the display of the operation in + the RBAC UX and the audit logs UX. + :type origin: str + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.display = kwargs.get('display', None) + self.origin = kwargs.get('origin', None) + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = kwargs.get('provider', None) + self.resource = kwargs.get('resource', None) + self.operation = kwargs.get('operation', None) + self.description = kwargs.get('description', None) + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: list[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = None + + +class Scope(msrest.serialization.Model): + """Scope of the extension. It can be either Cluster or Namespace; but not both. + + :param cluster: Specifies that the scope of the extension is Cluster. + :type cluster: ~azure.mgmt.kubernetesconfiguration.models.ScopeCluster + :param namespace: Specifies that the scope of the extension is Namespace. + :type namespace: ~azure.mgmt.kubernetesconfiguration.models.ScopeNamespace + """ + + _attribute_map = { + 'cluster': {'key': 'cluster', 'type': 'ScopeCluster'}, + 'namespace': {'key': 'namespace', 'type': 'ScopeNamespace'}, + } + + def __init__( + self, + **kwargs + ): + super(Scope, self).__init__(**kwargs) + self.cluster = kwargs.get('cluster', None) + self.namespace = kwargs.get('namespace', None) + + +class ScopeCluster(msrest.serialization.Model): + """Specifies that the scope of the extension is Cluster. + + :param release_namespace: Namespace where the extension Release must be placed, for a Cluster + scoped extension. If this namespace does not exist, it will be created. + :type release_namespace: str + """ + + _attribute_map = { + 'release_namespace': {'key': 'releaseNamespace', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ScopeCluster, self).__init__(**kwargs) + self.release_namespace = kwargs.get('release_namespace', None) + + +class ScopeNamespace(msrest.serialization.Model): + """Specifies that the scope of the extension is Namespace. + + :param target_namespace: Namespace where the extension will be created for an Namespace scoped + extension. If this namespace does not exist, it will be created. + :type target_namespace: str + """ + + _attribute_map = { + 'target_namespace': {'key': 'targetNamespace', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ScopeNamespace, self).__init__(**kwargs) + self.target_namespace = kwargs.get('target_namespace', None) + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: ~azure.mgmt.kubernetesconfiguration.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(**kwargs) + self.system_data = None + self.repository_url = kwargs.get('repository_url', None) + self.operator_namespace = kwargs.get('operator_namespace', "default") + self.operator_instance_name = kwargs.get('operator_instance_name', None) + self.operator_type = kwargs.get('operator_type', None) + self.operator_params = kwargs.get('operator_params', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.operator_scope = kwargs.get('operator_scope', "cluster") + self.repository_public_key = None + self.ssh_known_hosts_contents = kwargs.get('ssh_known_hosts_contents', None) + self.enable_helm_operator = kwargs.get('enable_helm_operator', None) + self.helm_operator_properties = kwargs.get('helm_operator_properties', None) + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SupportedScopes(msrest.serialization.Model): + """Extension scopes. + + :param default_scope: Default extension scopes: cluster or namespace. + :type default_scope: str + :param cluster_scope_settings: Scope settings. + :type cluster_scope_settings: ~azure.mgmt.kubernetesconfiguration.models.ClusterScopeSettings + """ + + _attribute_map = { + 'default_scope': {'key': 'defaultScope', 'type': 'str'}, + 'cluster_scope_settings': {'key': 'clusterScopeSettings', 'type': 'ClusterScopeSettings'}, + } + + def __init__( + self, + **kwargs + ): + super(SupportedScopes, self).__init__(**kwargs) + self.default_scope = kwargs.get('default_scope', None) + self.cluster_scope_settings = kwargs.get('cluster_scope_settings', None) + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type 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, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = kwargs.get('created_by', None) + self.created_by_type = kwargs.get('created_by_type', None) + self.created_at = kwargs.get('created_at', None) + self.last_modified_by = kwargs.get('last_modified_by', None) + self.last_modified_by_type = kwargs.get('last_modified_by_type', None) + self.last_modified_at = kwargs.get('last_modified_at', None) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models_py3.py new file mode 100644 index 00000000000..23a4494072e --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models_py3.py @@ -0,0 +1,1446 @@ +# 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 datetime +from typing import Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._source_control_configuration_client_enums import * + + +class Resource(msrest.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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class 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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class ClusterScopeSettings(ProxyResource): + """Extension scope settings. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + :param allow_multiple_instances: Describes if multiple instances of the extension are allowed. + :type allow_multiple_instances: bool + :param default_release_namespace: Default extension release namespace. + :type default_release_namespace: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'allow_multiple_instances': {'key': 'properties.allowMultipleInstances', 'type': 'bool'}, + 'default_release_namespace': {'key': 'properties.defaultReleaseNamespace', 'type': 'str'}, + } + + def __init__( + self, + *, + allow_multiple_instances: Optional[bool] = None, + default_release_namespace: Optional[str] = None, + **kwargs + ): + super(ClusterScopeSettings, self).__init__(**kwargs) + self.allow_multiple_instances = allow_multiple_instances + self.default_release_namespace = default_release_namespace + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + *, + last_config_applied: Optional[datetime.datetime] = None, + message: Optional[str] = None, + message_level: Optional[Union[str, "MessageLevelType"]] = None, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = last_config_applied + self.message = message + self.message_level = message_level + + +class ErrorAdditionalInfo(msrest.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: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(msrest.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.kubernetesconfiguration.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.kubernetesconfiguration.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 + ): + super(ErrorDetail, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(msrest.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.). + + :param error: The error object. + :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + """ + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + *, + error: Optional["ErrorDetail"] = None, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = error + + +class Extension(ProxyResource): + """The Extension object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + :param identity: Identity of the Extension resource. + :type identity: ~azure.mgmt.kubernetesconfiguration.models.Identity + :ivar system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :param extension_type: Type of the Extension, of which this resource is an instance of. It + must be one of the Extension Types registered with Microsoft.KubernetesConfiguration by the + Extension publisher. + :type extension_type: str + :param auto_upgrade_minor_version: Flag to note if this extension participates in auto upgrade + of minor version, or not. + :type auto_upgrade_minor_version: bool + :param release_train: ReleaseTrain this extension participates in for auto-upgrade (e.g. + Stable, Preview, etc.) - only if autoUpgradeMinorVersion is 'true'. + :type release_train: str + :param version: Version of the extension for this extension, if it is 'pinned' to a specific + version. autoUpgradeMinorVersion must be 'false'. + :type version: str + :param scope: Scope at which the extension is installed. + :type scope: ~azure.mgmt.kubernetesconfiguration.models.Scope + :param configuration_settings: Configuration settings, as name-value pairs for configuring this + extension. + :type configuration_settings: dict[str, str] + :param configuration_protected_settings: Configuration settings that are sensitive, as + name-value pairs for configuring this extension. + :type configuration_protected_settings: dict[str, str] + :ivar provisioning_state: Status of installation of this extension. Possible values include: + "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState + :param statuses: Status from this extension. + :type statuses: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionStatus] + :ivar error_info: Error information from the Agent - e.g. errors during installation. + :vartype error_info: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :ivar custom_location_settings: Custom Location settings properties. + :vartype custom_location_settings: dict[str, str] + :ivar package_uri: Uri of the Helm package. + :vartype package_uri: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'error_info': {'readonly': True}, + 'custom_location_settings': {'readonly': True}, + 'package_uri': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'identity': {'key': 'identity', 'type': 'Identity'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'extension_type': {'key': 'properties.extensionType', 'type': 'str'}, + 'auto_upgrade_minor_version': {'key': 'properties.autoUpgradeMinorVersion', 'type': 'bool'}, + 'release_train': {'key': 'properties.releaseTrain', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'scope': {'key': 'properties.scope', 'type': 'Scope'}, + 'configuration_settings': {'key': 'properties.configurationSettings', 'type': '{str}'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'statuses': {'key': 'properties.statuses', 'type': '[ExtensionStatus]'}, + 'error_info': {'key': 'properties.errorInfo', 'type': 'ErrorDetail'}, + 'custom_location_settings': {'key': 'properties.customLocationSettings', 'type': '{str}'}, + 'package_uri': {'key': 'properties.packageUri', 'type': 'str'}, + } + + def __init__( + self, + *, + identity: Optional["Identity"] = None, + extension_type: Optional[str] = None, + auto_upgrade_minor_version: Optional[bool] = True, + release_train: Optional[str] = "Stable", + version: Optional[str] = None, + scope: Optional["Scope"] = None, + configuration_settings: Optional[Dict[str, str]] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + statuses: Optional[List["ExtensionStatus"]] = None, + **kwargs + ): + super(Extension, self).__init__(**kwargs) + self.identity = identity + self.system_data = None + self.extension_type = extension_type + self.auto_upgrade_minor_version = auto_upgrade_minor_version + self.release_train = release_train + self.version = version + self.scope = scope + self.configuration_settings = configuration_settings + self.configuration_protected_settings = configuration_protected_settings + self.provisioning_state = None + self.statuses = statuses + self.error_info = None + self.custom_location_settings = None + self.package_uri = None + + +class ExtensionsList(msrest.serialization.Model): + """Result of the request to list Extensions. It contains a list of Extension objects and a 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 Extensions within a Kubernetes cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.Extension] + :ivar next_link: URL to get the next set of extension objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[Extension]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionsList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ExtensionStatus(msrest.serialization.Model): + """Status from the extension. + + :param code: Status code provided by the Extension. + :type code: str + :param display_status: Short description of status of the extension. + :type display_status: str + :param level: Level of the status. Possible values include: "Error", "Warning", "Information". + Default value: "Information". + :type level: str or ~azure.mgmt.kubernetesconfiguration.models.LevelType + :param message: Detailed message of the status from the Extension. + :type message: str + :param time: DateLiteral (per ISO8601) noting the time of installation status. + :type time: str + """ + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'display_status': {'key': 'displayStatus', 'type': 'str'}, + 'level': {'key': 'level', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'time': {'key': 'time', 'type': 'str'}, + } + + def __init__( + self, + *, + code: Optional[str] = None, + display_status: Optional[str] = None, + level: Optional[Union[str, "LevelType"]] = "Information", + message: Optional[str] = None, + time: Optional[str] = None, + **kwargs + ): + super(ExtensionStatus, self).__init__(**kwargs) + self.code = code + self.display_status = display_status + self.level = level + self.message = message + self.time = time + + +class ExtensionType(msrest.serialization.Model): + """Represents an Extension Type. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :ivar release_trains: Extension release train: preview or stable. + :vartype release_trains: list[str] + :ivar cluster_types: Cluster types. Possible values include: "connectedClusters", + "managedClusters". + :vartype cluster_types: str or ~azure.mgmt.kubernetesconfiguration.models.ClusterTypes + :ivar supported_scopes: Extension scopes. + :vartype supported_scopes: ~azure.mgmt.kubernetesconfiguration.models.SupportedScopes + """ + + _validation = { + 'system_data': {'readonly': True}, + 'release_trains': {'readonly': True}, + 'cluster_types': {'readonly': True}, + 'supported_scopes': {'readonly': True}, + } + + _attribute_map = { + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + 'release_trains': {'key': 'properties.releaseTrains', 'type': '[str]'}, + 'cluster_types': {'key': 'properties.clusterTypes', 'type': 'str'}, + 'supported_scopes': {'key': 'properties.supportedScopes', 'type': 'SupportedScopes'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionType, self).__init__(**kwargs) + self.system_data = None + self.release_trains = None + self.cluster_types = None + self.supported_scopes = None + + +class ExtensionTypeList(msrest.serialization.Model): + """List Extension Types. + + :param value: The list of Extension Types. + :type value: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionType] + :param next_link: The link to fetch the next page of Extension Types. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ExtensionType]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["ExtensionType"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(ExtensionTypeList, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class ExtensionVersionList(msrest.serialization.Model): + """List versions for an Extension. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param versions: Versions available for this Extension Type. + :type versions: + list[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionListVersionsItem] + :param next_link: The link to fetch the next page of Extension Types. + :type next_link: str + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + """ + + _validation = { + 'system_data': {'readonly': True}, + } + + _attribute_map = { + 'versions': {'key': 'versions', 'type': '[ExtensionVersionListVersionsItem]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + *, + versions: Optional[List["ExtensionVersionListVersionsItem"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(ExtensionVersionList, self).__init__(**kwargs) + self.versions = versions + self.next_link = next_link + self.system_data = None + + +class ExtensionVersionListVersionsItem(msrest.serialization.Model): + """ExtensionVersionListVersionsItem. + + :param release_train: The release train for this Extension Type. + :type release_train: str + :param versions: Versions available for this Extension Type and release train. + :type versions: list[str] + """ + + _attribute_map = { + 'release_train': {'key': 'releaseTrain', 'type': 'str'}, + 'versions': {'key': 'versions', 'type': '[str]'}, + } + + def __init__( + self, + *, + release_train: Optional[str] = None, + versions: Optional[List[str]] = None, + **kwargs + ): + super(ExtensionVersionListVersionsItem, self).__init__(**kwargs) + self.release_train = release_train + self.versions = versions + + +class FluxConfiguration(ProxyResource): + """The Flux Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :param scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type scope: str or ~azure.mgmt.kubernetesconfiguration.models.ScopeType + :param namespace: The namespace to which this configuration is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type namespace: str + :param source_kind: Source Kind to pull the configuration data from. Possible values include: + "GitRepository". + :type source_kind: str or ~azure.mgmt.kubernetesconfiguration.models.SourceKindType + :param suspend: Whether this configuration should suspend its reconciliation of its + kustomizations and sources. + :type suspend: bool + :param git_repository: Parameters to reconcile to the GitRepository source kind type. + :type git_repository: ~azure.mgmt.kubernetesconfiguration.models.GitRepositoryDefinition + :param kustomizations: Array of kustomizations used to reconcile the artifact pulled by the + source type on the cluster. + :type kustomizations: list[~azure.mgmt.kubernetesconfiguration.models.KustomizationDefinition] + :param configuration_protected_settings: Key-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :ivar statuses: Statuses of the Flux Kubernetes resources created by the fluxConfiguration or + created by the managed objects provisioned by the fluxConfiguration. + :vartype statuses: list[dict[str, any]] + :ivar repository_public_key: Public Key associated with this fluxConfiguration (either + generated within the cluster or provided by the user). + :vartype repository_public_key: str + :ivar last_synced_time: Datetime the fluxConfiguration has been synced with the Azure control + plane. + :vartype last_synced_time: str + :ivar last_synced_commit: Branch and SHA of the last source commit synced with the cluster. + :vartype last_synced_commit: str + :ivar last_config_applied_time: Datetime the fluxConfiguration was last applied. + :vartype last_config_applied_time: str + :ivar sync_state: Combined status of the Flux Kubernetes resources created by the + fluxConfiguration or created by the managed objects. Possible values include: "compliant", + "non-compliant", "syncing". Default value: "syncing". + :vartype sync_state: str or ~azure.mgmt.kubernetesconfiguration.models.SyncStateType + :ivar provisioning_state: Status of the creation of the fluxConfiguration. Possible values + include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState + :ivar message: Error message returned to the user in the case of provisioning failure. + :vartype message: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'statuses': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'last_synced_time': {'readonly': True}, + 'last_synced_commit': {'readonly': True}, + 'last_config_applied_time': {'readonly': True}, + 'sync_state': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'message': {'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'}, + 'scope': {'key': 'properties.scope', 'type': 'str'}, + 'namespace': {'key': 'properties.namespace', 'type': 'str'}, + 'source_kind': {'key': 'properties.sourceKind', 'type': 'str'}, + 'suspend': {'key': 'properties.suspend', 'type': 'bool'}, + 'git_repository': {'key': 'properties.gitRepository', 'type': 'GitRepositoryDefinition'}, + 'kustomizations': {'key': 'properties.kustomizations', 'type': '[KustomizationDefinition]'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'statuses': {'key': 'properties.statuses', 'type': '[{object}]'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'last_synced_time': {'key': 'properties.lastSyncedTime', 'type': 'str'}, + 'last_synced_commit': {'key': 'properties.lastSyncedCommit', 'type': 'str'}, + 'last_config_applied_time': {'key': 'properties.lastConfigAppliedTime', 'type': 'str'}, + 'sync_state': {'key': 'properties.syncState', 'type': 'str'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'message': {'key': 'properties.message', 'type': 'str'}, + } + + def __init__( + self, + *, + scope: Optional[Union[str, "ScopeType"]] = "cluster", + namespace: Optional[str] = "default", + source_kind: Optional[Union[str, "SourceKindType"]] = None, + suspend: Optional[bool] = False, + git_repository: Optional["GitRepositoryDefinition"] = None, + kustomizations: Optional[List["KustomizationDefinition"]] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + **kwargs + ): + super(FluxConfiguration, self).__init__(**kwargs) + self.system_data = None + self.scope = scope + self.namespace = namespace + self.source_kind = source_kind + self.suspend = suspend + self.git_repository = git_repository + self.kustomizations = kustomizations + self.configuration_protected_settings = configuration_protected_settings + self.statuses = None + self.repository_public_key = None + self.last_synced_time = None + self.last_synced_commit = None + self.last_config_applied_time = None + self.sync_state = None + self.provisioning_state = None + self.message = None + + +class FluxConfigurationsList(msrest.serialization.Model): + """Result of the request to list Flux Configurations. It contains a list of FluxConfiguration objects and a 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 Flux Configurations within a Kubernetes cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FluxConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FluxConfigurationsList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class GitRepositoryDefinition(msrest.serialization.Model): + """Parameters to reconcile to the GitRepository source kind type. + + :param url: The URL to sync for the flux configuration git repository. + :type url: str + :param timeout: The maximum time to attempt to reconcile the cluster git repository source with + the remote. + :type timeout: str + :param sync_interval: The interval at which to re-reconcile the cluster git repository source + with the remote. + :type sync_interval: str + :param repository_ref: The source reference for the GitRepository object. + :type repository_ref: ~azure.mgmt.kubernetesconfiguration.models.RepositoryRefDefinition + :param ssh_known_hosts: Base64-encoded known_hosts value containing public SSH keys required to + access private git repositories over SSH. + :type ssh_known_hosts: str + :param https_user: HTTPS username used to access private git repositories over HTTPS. + :type https_user: str + :param auth_ref_override: Name of a local secret on the Kubernetes cluster to use as the + authentication secret rather than the managed or user-provided configuration secrets. + :type auth_ref_override: str + """ + + _attribute_map = { + 'url': {'key': 'url', 'type': 'str'}, + 'timeout': {'key': 'timeout', 'type': 'str'}, + 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, + 'repository_ref': {'key': 'repositoryRef', 'type': 'RepositoryRefDefinition'}, + 'ssh_known_hosts': {'key': 'sshKnownHosts', 'type': 'str'}, + 'https_user': {'key': 'httpsUser', 'type': 'str'}, + 'auth_ref_override': {'key': 'authRefOverride', 'type': 'str'}, + } + + def __init__( + self, + *, + url: Optional[str] = None, + timeout: Optional[str] = None, + sync_interval: Optional[str] = None, + repository_ref: Optional["RepositoryRefDefinition"] = None, + ssh_known_hosts: Optional[str] = None, + https_user: Optional[str] = None, + auth_ref_override: Optional[str] = None, + **kwargs + ): + super(GitRepositoryDefinition, self).__init__(**kwargs) + self.url = url + self.timeout = timeout + self.sync_interval = sync_interval + self.repository_ref = repository_ref + self.ssh_known_hosts = ssh_known_hosts + self.https_user = https_user + self.auth_ref_override = auth_ref_override + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + *, + chart_version: Optional[str] = None, + chart_values: Optional[str] = None, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = chart_version + self.chart_values = chart_values + + +class Identity(msrest.serialization.Model): + """Identity for the resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal ID of resource identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of resource. + :vartype tenant_id: str + :ivar type: The identity type. Default value: "SystemAssigned". + :vartype type: str + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + 'type': {'constant': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + type = "SystemAssigned" + + def __init__( + self, + **kwargs + ): + super(Identity, self).__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + + +class KustomizationDefinition(msrest.serialization.Model): + """KustomizationDefinition. + + :param name: The name of the Kustomization object to create on the cluster. + :type name: str + :param path: The path in the source reference to reconcile on the cluster. + :type path: str + :param depends_on: Specifies other Kustomizations that this Kustomization depends on. This + Kustomization will not reconcile until all dependencies have completed their reconciliation. + :type depends_on: list[str] + :param timeout: The maximum time to attempt to reconcile the Kustomization on the cluster. + :type timeout: str + :param sync_interval: The interval at which to re-reconcile the Kustomization on the cluster. + :type sync_interval: str + :param retry_interval: The interval at which to re-reconcile the Kustomization on the cluster + in the event of failure on reconciliation. + :type retry_interval: str + :param prune: Enable/disable garbage collections of Kubernetes objects created by this + Kustomization. + :type prune: bool + :param validation: Specify whether to validate the Kubernetes objects referenced in the + Kustomization before applying them to the cluster. Possible values include: "none", "client", + "server". Default value: "none". + :type validation: str or ~azure.mgmt.kubernetesconfiguration.models.KustomizationValidationType + :param force: Enable/disable re-creating Kubernetes resources on the cluster when patching + fails due to an immutable field change. + :type force: bool + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'path': {'key': 'path', 'type': 'str'}, + 'depends_on': {'key': 'dependsOn', 'type': '[str]'}, + 'timeout': {'key': 'timeout', 'type': 'str'}, + 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, + 'retry_interval': {'key': 'retryInterval', 'type': 'str'}, + 'prune': {'key': 'prune', 'type': 'bool'}, + 'validation': {'key': 'validation', 'type': 'str'}, + 'force': {'key': 'force', 'type': 'bool'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + path: Optional[str] = "", + depends_on: Optional[List[str]] = None, + timeout: Optional[str] = None, + sync_interval: Optional[str] = None, + retry_interval: Optional[str] = None, + prune: Optional[bool] = None, + validation: Optional[Union[str, "KustomizationValidationType"]] = "none", + force: Optional[bool] = None, + **kwargs + ): + super(KustomizationDefinition, self).__init__(**kwargs) + self.name = name + self.path = path + self.depends_on = depends_on + self.timeout = timeout + self.sync_interval = sync_interval + self.retry_interval = retry_interval + self.prune = prune + self.validation = validation + self.force = force + + +class OperationStatusList(msrest.serialization.Model): + """The async operations in progress, in the cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of async operations in progress, in the cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult] + :ivar next_link: URL to get the next set of Operation Result objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[OperationStatusResult]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationStatusList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class OperationStatusResult(msrest.serialization.Model): + """The current status of an async operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param id: Fully qualified ID for the async operation. + :type id: str + :param name: Name of the async operation. + :type name: str + :param status: Required. Operation status. + :type status: str + :param properties: Additional information, if available. + :type properties: dict[str, str] + :ivar error: If present, details of the operation error. + :vartype error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + """ + + _validation = { + 'status': {'required': True}, + 'error': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'status': {'key': 'status', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{str}'}, + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + *, + status: str, + id: Optional[str] = None, + name: Optional[str] = None, + properties: Optional[Dict[str, str]] = None, + **kwargs + ): + super(OperationStatusResult, self).__init__(**kwargs) + self.id = id + self.name = name + self.status = status + self.properties = properties + self.error = None + + +class RepositoryRefDefinition(msrest.serialization.Model): + """The source reference for the GitRepository object. + + :param branch: The git repository branch name to checkout. + :type branch: str + :param tag: The git repository tag name to checkout. This takes precedence over branch. + :type tag: str + :param semver: The semver range used to match against git repository tags. This takes + precedence over tag. + :type semver: str + :param commit: The commit SHA to checkout. This value must be combined with the branch name to + be valid. This takes precedence over semver. + :type commit: str + """ + + _attribute_map = { + 'branch': {'key': 'branch', 'type': 'str'}, + 'tag': {'key': 'tag', 'type': 'str'}, + 'semver': {'key': 'semver', 'type': 'str'}, + 'commit': {'key': 'commit', 'type': 'str'}, + } + + def __init__( + self, + *, + branch: Optional[str] = None, + tag: Optional[str] = None, + semver: Optional[str] = None, + commit: Optional[str] = None, + **kwargs + ): + super(RepositoryRefDefinition, self).__init__(**kwargs) + self.branch = branch + self.tag = tag + self.semver = semver + self.commit = commit + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: ~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationDisplay + :param origin: The intended executor of the operation;governs the display of the operation in + the RBAC UX and the audit logs UX. + :type origin: str + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["ResourceProviderOperationDisplay"] = None, + origin: Optional[str] = None, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = name + self.display = display + self.origin = origin + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _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, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: list[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["ResourceProviderOperation"]] = None, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = value + self.next_link = None + + +class Scope(msrest.serialization.Model): + """Scope of the extension. It can be either Cluster or Namespace; but not both. + + :param cluster: Specifies that the scope of the extension is Cluster. + :type cluster: ~azure.mgmt.kubernetesconfiguration.models.ScopeCluster + :param namespace: Specifies that the scope of the extension is Namespace. + :type namespace: ~azure.mgmt.kubernetesconfiguration.models.ScopeNamespace + """ + + _attribute_map = { + 'cluster': {'key': 'cluster', 'type': 'ScopeCluster'}, + 'namespace': {'key': 'namespace', 'type': 'ScopeNamespace'}, + } + + def __init__( + self, + *, + cluster: Optional["ScopeCluster"] = None, + namespace: Optional["ScopeNamespace"] = None, + **kwargs + ): + super(Scope, self).__init__(**kwargs) + self.cluster = cluster + self.namespace = namespace + + +class ScopeCluster(msrest.serialization.Model): + """Specifies that the scope of the extension is Cluster. + + :param release_namespace: Namespace where the extension Release must be placed, for a Cluster + scoped extension. If this namespace does not exist, it will be created. + :type release_namespace: str + """ + + _attribute_map = { + 'release_namespace': {'key': 'releaseNamespace', 'type': 'str'}, + } + + def __init__( + self, + *, + release_namespace: Optional[str] = None, + **kwargs + ): + super(ScopeCluster, self).__init__(**kwargs) + self.release_namespace = release_namespace + + +class ScopeNamespace(msrest.serialization.Model): + """Specifies that the scope of the extension is Namespace. + + :param target_namespace: Namespace where the extension will be created for an Namespace scoped + extension. If this namespace does not exist, it will be created. + :type target_namespace: str + """ + + _attribute_map = { + 'target_namespace': {'key': 'targetNamespace', 'type': 'str'}, + } + + def __init__( + self, + *, + target_namespace: Optional[str] = None, + **kwargs + ): + super(ScopeNamespace, self).__init__(**kwargs) + self.target_namespace = target_namespace + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: ~azure.mgmt.kubernetesconfiguration.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + *, + repository_url: Optional[str] = None, + operator_namespace: Optional[str] = "default", + operator_instance_name: Optional[str] = None, + operator_type: Optional[Union[str, "OperatorType"]] = None, + operator_params: Optional[str] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + operator_scope: Optional[Union[str, "OperatorScopeType"]] = "cluster", + ssh_known_hosts_contents: Optional[str] = None, + enable_helm_operator: Optional[bool] = None, + helm_operator_properties: Optional["HelmOperatorProperties"] = None, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(**kwargs) + self.system_data = None + self.repository_url = repository_url + self.operator_namespace = operator_namespace + self.operator_instance_name = operator_instance_name + self.operator_type = operator_type + self.operator_params = operator_params + self.configuration_protected_settings = configuration_protected_settings + self.operator_scope = operator_scope + self.repository_public_key = None + self.ssh_known_hosts_contents = ssh_known_hosts_contents + self.enable_helm_operator = enable_helm_operator + self.helm_operator_properties = helm_operator_properties + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SupportedScopes(msrest.serialization.Model): + """Extension scopes. + + :param default_scope: Default extension scopes: cluster or namespace. + :type default_scope: str + :param cluster_scope_settings: Scope settings. + :type cluster_scope_settings: ~azure.mgmt.kubernetesconfiguration.models.ClusterScopeSettings + """ + + _attribute_map = { + 'default_scope': {'key': 'defaultScope', 'type': 'str'}, + 'cluster_scope_settings': {'key': 'clusterScopeSettings', 'type': 'ClusterScopeSettings'}, + } + + def __init__( + self, + *, + default_scope: Optional[str] = None, + cluster_scope_settings: Optional["ClusterScopeSettings"] = None, + **kwargs + ): + super(SupportedScopes, self).__init__(**kwargs) + self.default_scope = default_scope + self.cluster_scope_settings = cluster_scope_settings + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type 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, "CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs + ): + super(SystemData, self).__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/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py new file mode 100644 index 00000000000..097c14df789 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py @@ -0,0 +1,148 @@ +# 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, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class ClusterTypes(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Cluster types + """ + + CONNECTED_CLUSTERS = "connectedClusters" + MANAGED_CLUSTERS = "managedClusters" + +class ComplianceStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The compliance state of the configuration. + """ + + PENDING = "Pending" + COMPLIANT = "Compliant" + NONCOMPLIANT = "Noncompliant" + INSTALLED = "Installed" + FAILED = "Failed" + +class CreatedByType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The type of identity that created the resource. + """ + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + +class Enum0(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MICROSOFT_CONTAINER_SERVICE = "Microsoft.ContainerService" + MICROSOFT_KUBERNETES = "Microsoft.Kubernetes" + +class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MANAGED_CLUSTERS = "managedClusters" + CONNECTED_CLUSTERS = "connectedClusters" + +class Enum9(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MANAGED_CLUSTERS = "managedClusters" + CONNECTED_CLUSTERS = "connectedClusters" + +class KustomizationValidationType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Specify whether to validate the Kubernetes objects referenced in the Kustomization before + applying them to the cluster. + """ + + NONE = "none" + CLIENT = "client" + SERVER = "server" + +class LevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Level of the status. + """ + + ERROR = "Error" + WARNING = "Warning" + INFORMATION = "Information" + +class MessageLevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Level of the message. + """ + + ERROR = "Error" + WARNING = "Warning" + INFORMATION = "Information" + +class OperatorScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Scope at which the operator will be installed. + """ + + CLUSTER = "cluster" + NAMESPACE = "namespace" + +class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Type of the operator + """ + + FLUX = "Flux" + +class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The provisioning state of the resource. + """ + + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + CREATING = "Creating" + UPDATING = "Updating" + DELETING = "Deleting" + +class ProvisioningStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The provisioning state of the resource provider. + """ + + ACCEPTED = "Accepted" + DELETING = "Deleting" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + +class ScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Scope at which the configuration will be installed. + """ + + CLUSTER = "cluster" + NAMESPACE = "namespace" + +class SourceKindType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Source Kind to pull the configuration data from. + """ + + GIT_REPOSITORY = "GitRepository" + +class SyncStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Compliance state of the cluster object. + """ + + COMPLIANT = "compliant" + NON_COMPLIANT = "non-compliant" + SYNCING = "syncing" diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py new file mode 100644 index 00000000000..84aa36f0694 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py @@ -0,0 +1,31 @@ +# 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 ._flux_configurations_operations import FluxConfigurationsOperations +from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations +from ._extensions_operations import ExtensionsOperations +from ._operation_status_operations import OperationStatusOperations +from ._cluster_extension_type_operations import ClusterExtensionTypeOperations +from ._cluster_extension_types_operations import ClusterExtensionTypesOperations +from ._extension_type_versions_operations import ExtensionTypeVersionsOperations +from ._location_extension_types_operations import LocationExtensionTypesOperations +from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations + +__all__ = [ + 'FluxConfigurationsOperations', + 'FluxConfigOperationStatusOperations', + 'ExtensionsOperations', + 'OperationStatusOperations', + 'ClusterExtensionTypeOperations', + 'ClusterExtensionTypesOperations', + 'ExtensionTypeVersionsOperations', + 'LocationExtensionTypesOperations', + 'SourceControlConfigurationsOperations', + 'Operations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py new file mode 100644 index 00000000000..f640b5aad94 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py @@ -0,0 +1,119 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ClusterExtensionTypeOperations(object): + """ClusterExtensionTypeOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_type, # type: Union[str, "_models.Enum9"] + cluster_name, # type: str + extension_type_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.ExtensionType" + """Get Extension Type details. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_type: The Kubernetes cluster resource name - either managedClusters (for AKS + clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum9 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_type_name: Extension type name. + :type extension_type_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionType, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.ExtensionType + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionType"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterType': self._serialize.url("cluster_type", cluster_type, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionTypeName': self._serialize.url("extension_type_name", extension_type_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionType', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterType}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensionTypes/{extensionTypeName}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py new file mode 100644 index 00000000000..8655e283e4c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py @@ -0,0 +1,127 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ClusterExtensionTypesOperations(object): + """ClusterExtensionTypesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ExtensionTypeList"] + """Get Extension Types. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionTypeList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/connectedClusters/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensionTypes'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py new file mode 100644 index 00000000000..f536e0aa28d --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.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 typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ExtensionTypeVersionsOperations(object): + """ExtensionTypeVersionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location, # type: str + extension_type_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ExtensionVersionList"] + """List available versions for an Extension Type. + + :param location: extension location. + :type location: str + :param extension_type_name: Extension type name. + :type extension_type_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionVersionList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionVersionList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'location': self._serialize.url("location", location, 'str'), + 'extensionTypeName': self._serialize.url("extension_type_name", extension_type_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionVersionList', pipeline_response) + list_of_elem = deserialized.versions + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KubernetesConfiguration/locations/{location}/extensionTypes/{extensionTypeName}/versions'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py new file mode 100644 index 00000000000..83323d2fc05 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py @@ -0,0 +1,505 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ExtensionsOperations(object): + """ExtensionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def _create_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_name, # type: str + extension, # type: "_models.Extension" + **kwargs # type: Any + ): + # type: (...) -> "_models.Extension" + cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(extension, 'Extension') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('Extension', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('Extension', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + def begin_create( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_name, # type: str + extension, # type: "_models.Extension" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.Extension"] + """Create a new Kubernetes Cluster Extension. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param extension: Properties necessary to Create an Extension. + :type extension: ~azure.mgmt.kubernetesconfiguration.models.Extension + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either Extension or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.kubernetesconfiguration.models.Extension] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + extension_name=extension_name, + extension=extension, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('Extension', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.Extension" + """Gets Kubernetes Cluster Extension. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Extension, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.Extension + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('Extension', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_name, # type: str + force_delete=None, # type: Optional[bool] + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + if force_delete is not None: + query_parameters['forceDelete'] = self._serialize.query("force_delete", force_delete, 'bool') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_name, # type: str + force_delete=None, # type: Optional[bool] + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """Delete a Kubernetes Cluster Extension. This will cause the Agent to Uninstall the extension + from the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param force_delete: Delete the extension resource in Azure - not the normal asynchronous + delete. + :type force_delete: bool + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + extension_name=extension_name, + force_delete=force_delete, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}'} # type: ignore + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ExtensionsList"] + """List all Extensions in the cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionsList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionsList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionsList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionsList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_config_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_config_operation_status_operations.py new file mode 100644 index 00000000000..950ba3486c8 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_config_operation_status_operations.py @@ -0,0 +1,123 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class FluxConfigOperationStatusOperations(object): + """FluxConfigOperationStatusOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + flux_configuration_name, # type: str + operation_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.OperationStatusResult" + """Get Async Operation status. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :param operation_id: operation Id. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationStatusResult, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationStatusResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}/operations/{operationId}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py new file mode 100644 index 00000000000..f2b55e3dd06 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py @@ -0,0 +1,501 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class FluxConfigurationsOperations(object): + """FluxConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + flux_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.FluxConfiguration" + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FluxConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FluxConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + def _create_or_update_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + flux_configuration_name, # type: str + flux_configuration, # type: "_models.FluxConfiguration" + **kwargs # type: Any + ): + # type: (...) -> "_models.FluxConfiguration" + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self._create_or_update_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(flux_configuration, 'FluxConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('FluxConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + def begin_create_or_update( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + flux_configuration_name, # type: str + flux_configuration, # type: "_models.FluxConfiguration" + **kwargs # type: Any + ): + # type: (...) -> LROPoller["_models.FluxConfiguration"] + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :param flux_configuration: Properties necessary to Create a FluxConfiguration. + :type flux_configuration: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either FluxConfiguration or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + flux_configuration_name=flux_configuration_name, + flux_configuration=flux_configuration, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize('FluxConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + flux_configuration_name, # type: str + force_delete=None, # type: Optional[bool] + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + if force_delete is not None: + query_parameters['forceDelete'] = self._serialize.query("force_delete", force_delete, 'bool') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + flux_configuration_name, # type: str + force_delete=None, # type: Optional[bool] + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param flux_configuration_name: Name of the Flux Configuration. + :type flux_configuration_name: str + :param force_delete: Delete the extension resource in Azure - not the normal asynchronous + delete. + :type force_delete: bool + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + flux_configuration_name=flux_configuration_name, + force_delete=force_delete, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'fluxConfigurationName': self._serialize.url("flux_configuration_name", flux_configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations/{fluxConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.FluxConfigurationsList"] + """List all Flux Configurations. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either FluxConfigurationsList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.FluxConfigurationsList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfigurationsList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('FluxConfigurationsList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/fluxConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py new file mode 100644 index 00000000000..d273c577dc1 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py @@ -0,0 +1,118 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class LocationExtensionTypesOperations(object): + """LocationExtensionTypesOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + location, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ExtensionTypeList"] + """List all Extension Types. + + :param location: extension location. + :type location: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'location': self._serialize.url("location", location, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionTypeList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KubernetesConfiguration/locations/{location}/extensionTypes'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py new file mode 100644 index 00000000000..9bb4a643ab2 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py @@ -0,0 +1,210 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class OperationStatusOperations(object): + """OperationStatusOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.OperationStatusList"] + """List Async Operations, currently in progress, in a cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either OperationStatusList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.OperationStatusList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('OperationStatusList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_name, # type: str + operation_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.OperationStatusResult" + """Get Async Operation status. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param operation_id: operation Id. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationStatusResult, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationStatusResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}/operations/{operationId}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operations.py new file mode 100644 index 00000000000..3e2bdacb973 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operations.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ResourceProviderOperationList"] + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..203755732f7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py @@ -0,0 +1,429 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations(object): + """SourceControlConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def create_or_update( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + source_control_configuration, # type: "_models.SourceControlConfiguration" + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.SourceControlConfigurationList"] + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/setup.cfg b/src/k8s-config/setup.cfg new file mode 100644 index 00000000000..3c6e79cf31d --- /dev/null +++ b/src/k8s-config/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal=1 diff --git a/src/k8s-config/setup.py b/src/k8s-config/setup.py new file mode 100644 index 00000000000..912117037d8 --- /dev/null +++ b/src/k8s-config/setup.py @@ -0,0 +1,60 @@ +#!/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. +# -------------------------------------------------------------------------------------------- + + +from codecs import open +from setuptools import setup, find_packages +try: + from azure_bdist_wheel import cmdclass +except ImportError: + from distutils import log as logger + logger.warn("Wheel is not available, disabling bdist_wheel hook") + +# TODO: Confirm this is the right version number you want and it matches your +# HISTORY.rst entry. +VERSION = '0.1.0' + +# The full list of classifiers is available at +# https://pypi.python.org/pypi?%3Aaction=list_classifiers +CLASSIFIERS = [ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'License :: OSI Approved :: MIT License', +] + +# TODO: Add any additional SDK dependencies here +DEPENDENCIES = [ + 'azure-cli-core' +] + +with open('README.rst', 'r', encoding='utf-8') as f: + README = f.read() +with open('HISTORY.rst', 'r', encoding='utf-8') as f: + HISTORY = f.read() + +setup( + name='k8s-config', + version=VERSION, + description='Microsoft Azure Command-Line Tools K8s-config Extension', + # TODO: Update author and email, if applicable + author='Microsoft Corporation', + author_email='azpycli@microsoft.com', + # TODO: consider pointing directly to your source code instead of the generic repo + url='https://github.com/Azure/azure-cli-extensions', + long_description=README + '\n\n' + HISTORY, + license='MIT', + classifiers=CLASSIFIERS, + packages=find_packages(), + install_requires=DEPENDENCIES, + package_data={'azext_k8s-config': ['azext_metadata.json']}, +) \ No newline at end of file From 81c5463c34ac24ba3079079d5abb5d6536e035fe Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 27 May 2021 15:14:52 -0700 Subject: [PATCH 02/61] Base implementation of CLI commands --- src/k8s-config/azext_k8s_config/_params.py | 97 +++++++++++++++++-- .../azext_k8s_config/_validators.py | 53 +++++++--- src/k8s-config/azext_k8s_config/custom.py | 71 +++++++++++++- src/k8s-config/azext_k8s_config/utils.py | 10 ++ 4 files changed, 207 insertions(+), 24 deletions(-) create mode 100644 src/k8s-config/azext_k8s_config/utils.py diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 9ac9ffb88ce..c473e0a675c 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -4,20 +4,105 @@ # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long -from knack.arguments import CLIArgumentType +from azure.cli.core.commands.parameters import ( + get_three_state_flag, + get_enum_type, + tags_type +) def load_arguments(self, _): from azure.cli.core.commands.parameters import tags_type from azure.cli.core.commands.validators import get_default_location_from_resource_group - - k8s-config_name_type = CLIArgumentType(options_list='--k8s-config-name-name', help='Name of the K8s-config.', id_part='name') + from ._validators import validate_configuration_name, validate_namespace with self.argument_context('k8s-config') as c: c.argument('tags', tags_type) c.argument('location', validator=get_default_location_from_resource_group) - c.argument('k8s-config_name', k8s-config_name_type, options_list=['--name', '-n']) + c.argument('name', + options_list=['--name', '-n'], + help='Name of the configuration', + validator=validate_configuration_name) + c.argument('cluster_name', + options_list=['--cluster-name', '-c'], + help='Name of the Kubernetes cluster') + c.argument('cluster_type', + arg_type=get_enum_type(['connectedClusters', 'managedClusters']), + help='Specify Arc clusters or AKS managed clusters.') + + with self.argument_context('k8s-config flux source') as c: + c.argument('scope', + arg_type=get_enum_type(['namespace', 'cluster']), + help="Specify scope of the operator to be 'namespace' or 'cluster'") + c.argument('namespace', + help='Specify namespace to deploy the configuration', + validator=validate_namespace) + c.argument('kind', + arg_type=get_enum_type(['git']), + options_list=['--kind', '-k'], + help='Specify the source kind to reconcile') + c.argument('url', + help='Specify namespace to deploy the configuration') + c.argument('timeout', + help='Specify the source kind to reconcile') + c.argument('sync_interval', + options_list=['--interval', '--sync-interval'], + help='Specify the source kind to reconcile') + c.argument('branch', + arg_group="Repo Ref", + help='Specify the branch to reconcile the git repository source kind') + c.argument('tag', + arg_group="Repo Ref", + help='Specify the branch to reconcile the git repository source kind') + c.argument('semver', + arg_group="Repo Ref", + help='Specify the branch to reconcile the git repository source kind') + c.argument('commit', + arg_group="Repo Ref", + help='Specify the branch to reconcile the git repository source kind') + c.argument('auth_ref_override', + options_list=['--auth-ref-override', '--auth-ref'], + help='Specify the branch to reconcile the git repository source kind') + c.argument('ssh_private_key', + arg_group="Auth", + help='Specify Base64-encoded private ssh key for private repository sync') + c.argument('ssh_private_key_file', + arg_group="Auth", + help='Specify filepath to private ssh key for private repository sync') + c.argument('https_user', + arg_group="Auth", + help='Specify HTTPS username for private repository sync') + c.argument('https_key', + arg_group="Auth", + help='Specify HTTPS token/password for private repository sync') + c.argument('ssh_known_hosts', + arg_group="Auth", + help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') + c.argument('ssh_known_hosts_file', + arg_group="Auth", + help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') - with self.argument_context('k8s-config list') as c: - c.argument('k8s-config_name', k8s-config_name_type, id_part=None) + with self.argument_context('k8s-config flux kustomization') as c: + c.argument('config_name', + help='Specify the name of the configuration to create the kustomization', + validator=validate_namespace) + c.argument('path', + help='Specify the name of the configuration to create the kustomization') + c.argument('dependencies', + options_list=['--depends', '--dependencies'], + help='Specify the name of the configuration to create the kustomization') + c.argument('timeout', + help='Specify the source kind to reconcile') + c.argument('sync_interval', + options_list=['--interval', '--sync-interval'], + help='Specify the source kind to reconcile') + c.argument('retry_interval', + help='Specify the source kind to reconcile') + c.argument('prune', + help='Specify the source kind to reconcile') + c.argument('force', + help='Specify the source kind to reconcile') + c.argument('validation', + arg_type=get_enum_type(['none', 'client', 'server']), + help='Specify the source kind to reconcile') diff --git a/src/k8s-config/azext_k8s_config/_validators.py b/src/k8s-config/azext_k8s_config/_validators.py index 821630f5f34..a6e1f807076 100644 --- a/src/k8s-config/azext_k8s_config/_validators.py +++ b/src/k8s-config/azext_k8s_config/_validators.py @@ -3,18 +3,43 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +import re +from azure.cli.core.azclierror import InvalidArgumentValueError -def example_name_or_id_validator(cmd, namespace): - # Example of a storage account name or ID validator. - # See: https://github.com/Azure/azure-cli/blob/dev/doc/authoring_command_modules/authoring_commands.md#supporting-name-or-id-parameters - from azure.cli.core.commands.client_factory import get_subscription_id - from msrestazure.tools import is_valid_resource_id, resource_id - if namespace.storage_account: - if not is_valid_resource_id(namespace.RESOURCE): - namespace.storage_account = resource_id( - subscription=get_subscription_id(cmd.cli_ctx), - resource_group=namespace.resource_group_name, - namespace='Microsoft.Storage', - type='storageAccounts', - name=namespace.storage_account - ) + +# Parameter-Level Validation +def validate_configuration_type(configuration_type): + if configuration_type.lower() != 'sourcecontrolconfiguration': + raise InvalidArgumentValueError( + 'Invalid configuration-type', + 'Try specifying the valid value "sourceControlConfiguration"') + + +def validate_namespace(namespace): + if namespace.namespace: + __validate_k8s_name(namespace.namespace, "--namespace", 23) + + +def validate_operator_instance_name(namespace): + if namespace.operator_instance_name: + __validate_k8s_name(namespace.operator_instance_name, "--operator-instance-name", 23) + + +def validate_configuration_name(namespace): + __validate_k8s_name(namespace.name, "--name", 63) + + +# Helper +def __validate_k8s_name(param_value, param_name, max_len): + if len(param_value) > max_len: + raise InvalidArgumentValueError( + 'Error! Invalid {0}'.format(param_name), + 'Parameter {0} can be a maximum of {1} characters'.format(param_name, max_len)) + if not re.match(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?$', param_value): + if param_value[0] == "-" or param_value[-1] == "-": + raise InvalidArgumentValueError( + 'Error! Invalid {0}'.format(param_name), + 'Parameter {0} cannot begin or end with a hyphen'.format(param_name)) + raise InvalidArgumentValueError( + 'Error! Invalid {0}'.format(param_name), + 'Parameter {0} can only contain lowercase alphanumeric characters and hyphens'.format(param_name)) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 47df9f884f3..9d147741497 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -4,13 +4,76 @@ # -------------------------------------------------------------------------------------------- from knack.util import CLIError +from .vendored_sdks.models import ( + FluxConfiguration, + GitRepositoryDefinition, + KustomizationDefinition, + RepositoryRefDefinition +) +from .utils import get_cluster_type +from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property -def flux_create_source(client, resource_group_name, cluster_name, name, cluster_type): - raise CLIError('TODO: Implement `k8s-config create`') +def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, + scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, + auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, + ssh_known_hosts=None, ssh_known_hosts_file=None): -def flux_create_kustomization(client, resource_group_name, cluster_name, name, cluster_type): - raise CLIError('TODO: Implement `k8s-config create`') + # Determine ClusterRP + cluster_rp = get_cluster_type(cluster_type) + + repository_ref = RepositoryRefDefinition( + branch=branch, + tag=tag, + semver=semver, + commit=commit + ) + + git_repository = GitRepositoryDefinition( + url=url, + timeout=timeout, + sync_interval=sync_interval, + repository_ref=repository_ref, + ssh_known_hosts=ssh_known_hosts, + https_user=https_user, + auth_ref_override=auth_ref_override + ) + + flux_configuration = FluxConfiguration( + scope=scope, + namespace=namespace, + source_kind=kind, + timeout=timeout, + sync_interval=sync_interval, + git_repository=git_repository, + kustomizations=[] + ) + # cache the payload if --defer used or send to Azure + return cached_put(cmd, client.create_or_update, resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) + +def flux_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, + dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): + + # Determine ClusterRP + cluster_rp = get_cluster_type(cluster_type) + + flux_configuration = cached_get(cmd, client.get, resource_group_name, cluster_rp, cluster_type, cluster_name, config_name) + + kustomization = KustomizationDefinition( + name=name, + path=path, + dependencies=dependencies, + timeout=timeout, + sync_interval=sync_interval, + retry_interval=retry_interval, + prune=prune, + validation=validation, + force=force + ) + + upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') + flux_configuration = cached_put(cmd, client.create_or_update, resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration).result() + return get_property(flux_configuration.kustomizations, name) def flux_delete(client, resource_group_name, cluster_name, name, cluster_type): raise CLIError('TODO: Implement `k8s-config create`') diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py new file mode 100644 index 00000000000..73e8c579365 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -0,0 +1,10 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +def get_cluster_type(cluster_type): + if cluster_type.lower() == 'connectedclusters': + return 'Microsoft.Kubernetes' + # Since cluster_type is an enum of only two values, if not connectedClusters, it will be managedClusters. + return 'Microsoft.ContainerService' \ No newline at end of file From c20c3c840477b36b84b37e056616d15f3731c8b3 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 2 Jun 2021 13:51:07 -0700 Subject: [PATCH 03/61] Add create scenario and cleanup in consts --- src/k8s-config/azext_k8s_config/__init__.py | 6 +- .../azext_k8s_config/_client_factory.py | 14 +- src/k8s-config/azext_k8s_config/_help.py | 25 +- src/k8s-config/azext_k8s_config/_params.py | 121 +++++++--- .../azext_k8s_config/_validators.py | 45 ---- src/k8s-config/azext_k8s_config/action.py | 37 +++ src/k8s-config/azext_k8s_config/commands.py | 19 +- src/k8s-config/azext_k8s_config/consts.py | 90 ++++++++ src/k8s-config/azext_k8s_config/custom.py | 217 ++++++++++++++---- .../azext_k8s_config/tests/__init__.py | 2 +- .../azext_k8s_config/tests/latest/__init__.py | 2 +- .../tests/latest/test_k8s-config_scenario.py | 26 +-- src/k8s-config/azext_k8s_config/utils.py | 84 ++++++- src/k8s-config/azext_k8s_config/validators.py | 207 +++++++++++++++++ src/k8s-config/setup.py | 2 +- 15 files changed, 708 insertions(+), 189 deletions(-) delete mode 100644 src/k8s-config/azext_k8s_config/_validators.py create mode 100644 src/k8s-config/azext_k8s_config/action.py create mode 100644 src/k8s-config/azext_k8s_config/consts.py create mode 100644 src/k8s-config/azext_k8s_config/validators.py diff --git a/src/k8s-config/azext_k8s_config/__init__.py b/src/k8s-config/azext_k8s_config/__init__.py index edc0dafcd39..89b3a9f5821 100644 --- a/src/k8s-config/azext_k8s_config/__init__.py +++ b/src/k8s-config/azext_k8s_config/__init__.py @@ -12,12 +12,12 @@ class k8s_configCommandsLoader(AzCommandsLoader): def __init__(self, cli_ctx=None): from azure.cli.core.commands import CliCommandType - from azext_k8s_config._client_factory import cf_k8s_config + from azext_k8s_config._client_factory import k8s_config_client k8s_config_custom = CliCommandType( operations_tmpl='azext_k8s_config.custom#{}', - client_factory=cf_k8s_config) + client_factory=k8s_config_client) super(k8s_configCommandsLoader, self).__init__(cli_ctx=cli_ctx, - custom_command_type=k8s_config_custom) + custom_command_type=k8s_config_custom) def load_command_table(self, args): from azext_k8s_config.commands import load_command_table diff --git a/src/k8s-config/azext_k8s_config/_client_factory.py b/src/k8s-config/azext_k8s_config/_client_factory.py index 39bf4814422..27b5d6dfb39 100644 --- a/src/k8s-config/azext_k8s_config/_client_factory.py +++ b/src/k8s-config/azext_k8s_config/_client_factory.py @@ -3,12 +3,18 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +from azure.cli.core.commands.client_factory import get_mgmt_service_client -def cf_k8s_config(cli_ctx, *_): - from azure.cli.core.commands.client_factory import get_mgmt_service_client + +def k8s_config_client(cli_ctx, *_): from azext_k8s_config.vendored_sdks import SourceControlConfigurationClient return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient) -def cf_k8s_config_fc_operations(cli_ctx, _): - return cf_k8s_config(cli_ctx).flux_configurations +def k8s_config_fluxconfig_client(cli_ctx, _): + return k8s_config_client(cli_ctx).flux_configurations + + +def resource_providers_client(cli_ctx): + from azure.mgmt.resource import ResourceManagementClient + return get_mgmt_service_client(cli_ctx, ResourceManagementClient).providers diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 19900e3cfd3..5f70be8f1fd 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -12,27 +12,22 @@ short-summary: Commands to manage K8s-configs. """ -helps['k8s-config create'] = """ +helps['k8s-config flux create'] = """ type: command short-summary: Create a K8s-config. """ -helps['k8s-config list'] = """ +helps['k8s-config flux list'] = """ type: command short-summary: List K8s-configs. """ -# helps['k8s-config delete'] = """ -# type: command -# short-summary: Delete a K8s-config. -# """ - -# helps['k8s-config show'] = """ -# type: command -# short-summary: Show details of a K8s-config. -# """ +helps['k8s-config flux show'] = """ + type: command + short-summary: List K8s-configs. +""" -# helps['k8s-config update'] = """ -# type: command -# short-summary: Update a K8s-config. -# """ +helps['k8s-config flux delete'] = """ + type: command + short-summary: List K8s-configs. +""" diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index c473e0a675c..722ce14dd31 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -3,20 +3,21 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long +# pylint: disable=too-many-statements +from azure.cli.core.commands.validators import get_default_location_from_resource_group from azure.cli.core.commands.parameters import ( - get_three_state_flag, get_enum_type, tags_type ) +from .validators import validate_configuration_name, validate_namespace +from .action import KustomizationAddAction +from .consts import ( + GIT_CLI_KIND +) def load_arguments(self, _): - - from azure.cli.core.commands.parameters import tags_type - from azure.cli.core.commands.validators import get_default_location_from_resource_group - from ._validators import validate_configuration_name, validate_namespace - with self.argument_context('k8s-config') as c: c.argument('tags', tags_type) c.argument('location', validator=get_default_location_from_resource_group) @@ -31,7 +32,11 @@ def load_arguments(self, _): arg_type=get_enum_type(['connectedClusters', 'managedClusters']), help='Specify Arc clusters or AKS managed clusters.') - with self.argument_context('k8s-config flux source') as c: + with self.argument_context('k8s-config flux create') as c: + c.argument('kustomization', + options_list=['--kustomization', '-k'], + action=KustomizationAddAction, + nargs='+') c.argument('scope', arg_type=get_enum_type(['namespace', 'cluster']), help="Specify scope of the operator to be 'namespace' or 'cluster'") @@ -39,10 +44,10 @@ def load_arguments(self, _): help='Specify namespace to deploy the configuration', validator=validate_namespace) c.argument('kind', - arg_type=get_enum_type(['git']), - options_list=['--kind', '-k'], + arg_type=get_enum_type([GIT_CLI_KIND]), help='Specify the source kind to reconcile') c.argument('url', + options_list=['--url', '-u'], help='Specify namespace to deploy the configuration') c.argument('timeout', help='Specify the source kind to reconcile') @@ -83,26 +88,78 @@ def load_arguments(self, _): arg_group="Auth", help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') - with self.argument_context('k8s-config flux kustomization') as c: - c.argument('config_name', - help='Specify the name of the configuration to create the kustomization', - validator=validate_namespace) - c.argument('path', - help='Specify the name of the configuration to create the kustomization') - c.argument('dependencies', - options_list=['--depends', '--dependencies'], - help='Specify the name of the configuration to create the kustomization') - c.argument('timeout', - help='Specify the source kind to reconcile') - c.argument('sync_interval', - options_list=['--interval', '--sync-interval'], - help='Specify the source kind to reconcile') - c.argument('retry_interval', - help='Specify the source kind to reconcile') - c.argument('prune', - help='Specify the source kind to reconcile') - c.argument('force', - help='Specify the source kind to reconcile') - c.argument('validation', - arg_type=get_enum_type(['none', 'client', 'server']), - help='Specify the source kind to reconcile') + # with self.argument_context('k8s-config flux source') as c: + # c.argument('scope', + # arg_type=get_enum_type(['namespace', 'cluster']), + # help="Specify scope of the operator to be 'namespace' or 'cluster'") + # c.argument('namespace', + # help='Specify namespace to deploy the configuration', + # validator=validate_namespace) + # c.argument('kind', + # arg_type=get_enum_type(['git']), + # options_list=['--kind', '-k'], + # help='Specify the source kind to reconcile') + # c.argument('url', + # help='Specify namespace to deploy the configuration') + # c.argument('timeout', + # help='Specify the source kind to reconcile') + # c.argument('sync_interval', + # options_list=['--interval', '--sync-interval'], + # help='Specify the source kind to reconcile') + # c.argument('branch', + # arg_group="Repo Ref", + # help='Specify the branch to reconcile the git repository source kind') + # c.argument('tag', + # arg_group="Repo Ref", + # help='Specify the branch to reconcile the git repository source kind') + # c.argument('semver', + # arg_group="Repo Ref", + # help='Specify the branch to reconcile the git repository source kind') + # c.argument('commit', + # arg_group="Repo Ref", + # help='Specify the branch to reconcile the git repository source kind') + # c.argument('auth_ref_override', + # options_list=['--auth-ref-override', '--auth-ref'], + # help='Specify the branch to reconcile the git repository source kind') + # c.argument('ssh_private_key', + # arg_group="Auth", + # help='Specify Base64-encoded private ssh key for private repository sync') + # c.argument('ssh_private_key_file', + # arg_group="Auth", + # help='Specify filepath to private ssh key for private repository sync') + # c.argument('https_user', + # arg_group="Auth", + # help='Specify HTTPS username for private repository sync') + # c.argument('https_key', + # arg_group="Auth", + # help='Specify HTTPS token/password for private repository sync') + # c.argument('ssh_known_hosts', + # arg_group="Auth", + # help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') + # c.argument('ssh_known_hosts_file', + # arg_group="Auth", + # help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') + + # with self.argument_context('k8s-config flux kustomization') as c: + # c.argument('config_name', + # help='Specify the name of the configuration to create the kustomization', + # validator=validate_namespace) + # c.argument('path', + # help='Specify the name of the configuration to create the kustomization') + # c.argument('dependencies', + # options_list=['--depends', '--dependencies'], + # help='Specify the name of the configuration to create the kustomization') + # c.argument('timeout', + # help='Specify the source kind to reconcile') + # c.argument('sync_interval', + # options_list=['--interval', '--sync-interval'], + # help='Specify the source kind to reconcile') + # c.argument('retry_interval', + # help='Specify the source kind to reconcile') + # c.argument('prune', + # help='Specify the source kind to reconcile') + # c.argument('force', + # help='Specify the source kind to reconcile') + # c.argument('validation', + # arg_type=get_enum_type(['none', 'client', 'server']), + # help='Specify the source kind to reconcile') diff --git a/src/k8s-config/azext_k8s_config/_validators.py b/src/k8s-config/azext_k8s_config/_validators.py deleted file mode 100644 index a6e1f807076..00000000000 --- a/src/k8s-config/azext_k8s_config/_validators.py +++ /dev/null @@ -1,45 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import re -from azure.cli.core.azclierror import InvalidArgumentValueError - - -# Parameter-Level Validation -def validate_configuration_type(configuration_type): - if configuration_type.lower() != 'sourcecontrolconfiguration': - raise InvalidArgumentValueError( - 'Invalid configuration-type', - 'Try specifying the valid value "sourceControlConfiguration"') - - -def validate_namespace(namespace): - if namespace.namespace: - __validate_k8s_name(namespace.namespace, "--namespace", 23) - - -def validate_operator_instance_name(namespace): - if namespace.operator_instance_name: - __validate_k8s_name(namespace.operator_instance_name, "--operator-instance-name", 23) - - -def validate_configuration_name(namespace): - __validate_k8s_name(namespace.name, "--name", 63) - - -# Helper -def __validate_k8s_name(param_value, param_name, max_len): - if len(param_value) > max_len: - raise InvalidArgumentValueError( - 'Error! Invalid {0}'.format(param_name), - 'Parameter {0} can be a maximum of {1} characters'.format(param_name, max_len)) - if not re.match(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?$', param_value): - if param_value[0] == "-" or param_value[-1] == "-": - raise InvalidArgumentValueError( - 'Error! Invalid {0}'.format(param_name), - 'Parameter {0} cannot begin or end with a hyphen'.format(param_name)) - raise InvalidArgumentValueError( - 'Error! Invalid {0}'.format(param_name), - 'Parameter {0} can only contain lowercase alphanumeric characters and hyphens'.format(param_name)) diff --git a/src/k8s-config/azext_k8s_config/action.py b/src/k8s-config/azext_k8s_config/action.py new file mode 100644 index 00000000000..105ec48f3dd --- /dev/null +++ b/src/k8s-config/azext_k8s_config/action.py @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=protected-access + +import argparse +from azure.cli.core.azclierror import InvalidArgumentValueError +from .vendored_sdks.models import KustomizationDefinition +from .validators import validate_kustomization +from . import consts +from .utils import parse_dependencies + + +class KustomizationAddAction(argparse._AppendAction): + def __call__(self, parser, namespace, values, option_string=None): + validate_kustomization(values) + dependencies = [] + sync_interval = "" + kwargs = {} + for item in values: + try: + key, value = item.split('=', 1) + if key in consts.DEPENDENCY_KEYS: + dependencies = parse_dependencies(value) + elif key in consts.SYNC_INTERVAL_KEYS: + sync_interval = value + else: + kwargs[key] = value + except ValueError: + raise InvalidArgumentValueError('usage error: {} KEY=VALUE [KEY=VALUE ...]'.format(option_string)) + super(KustomizationAddAction, self).__call__( + parser, + namespace, + KustomizationDefinition(depends_on=dependencies, sync_interval=sync_interval, **kwargs), + option_string + ) diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index f7d3a80c22f..3049c30a8fd 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -5,18 +5,17 @@ # pylint: disable=line-too-long from azure.cli.core.commands import CliCommandType -from azext_k8s_config._client_factory import cf_k8s_config_fc_operations +from azext_k8s_config._client_factory import k8s_config_fluxconfig_client def load_command_table(self, _): - k8s_config_fc_sdk = CliCommandType( - operations_tmpl='azext_k8s_config.vendored_sdks.operations#FluxConfigurationsOperations.{}', - client_factory=cf_k8s_config_fc_operations) + k8s_config_fluxconfig_sdk = CliCommandType( + operations_tmpl='azext_k8s_config.vendored_sdks.operations#FluxConfigurationsOperations.{}', + client_factory=k8s_config_fluxconfig_client + ) - with self.command_group('k8s-config flux', k8s_config_fc_sdk, is_preview=True) as g: - g.custom_command('source create', "flux_create_source", supports_local_cache=True) - g.custom_command('kustomization create', "flux_create_kustomization", supports_local_cache=True) - g.custom_command('delete', 'flux_delete', confirmation=True) + with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_preview=True) as g: + g.custom_command('create', 'flux_config_create') g.command('list', "list") - g.show_command('show', 'get') - + g.custom_command('show', 'flux_config_show') + g.custom_command('delete', 'flux_config_delete', confirmation=True) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py new file mode 100644 index 00000000000..c95e8c4cd17 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -0,0 +1,90 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=line-too-long + +KUSTOMIZATION_REQUIRED_VALUES_MISSING_ERROR = "Error! Kustomization definition is invalid, required values {} not found" +KUSTOMIZATION_REQUIRED_VALUES_MISSING_HELP = "Add the required values to the Kustomization object and try again" + +REPOSITORY_REF_REQUIRED_VALUES_MISSING_ERROR = "Error! Repository reference is invalid" +REPOSITORY_REF_REQUIRED_VALUES_MISSING_HELP = "Specifying one of [--branch, --tag, --semver, --commit] is required" + +GIT_REPOSITORY_REQUIRED_VALUES_MISSING_ERROR = "Error! Git repository kind is missing required value {}" +GIT_REPOSITORY_REQUIRED_VALUES_MISSING_HELP = "Add missing git repository kind and try again" + +INVALID_DURATION_ERROR = "Error! Invalid {0}." +INVALID_DURATION_HELP = "Specify a valid ISO8601 duration and try again" + +INVALID_URL_ERROR = "Error! Invalid --url." +INVALID_URL_HELP = "Url must beginwith one of ['http://', 'https://', 'git@', 'ssh://']" + +INVALID_KUBERNETES_NAME_LENGTH_ERROR = "Error! Invalid {0}." +INVALID_KUBERNETES_NAME_LENGTH_HELP = "Parameter {0} can be a maximum of {1} characters. Specify a shorter name and try again." + +INVALID_KUBERNETES_NAME_HYPHEN_ERROR = "Error! Invalid {0}." +INVALID_KUBERNETES_NAME_HYPHEN_HELP = "Parameter {0} cannot begin or end with a hyphen." + +INVALID_KUBERNETES_NAME_ERROR = "Error! Invalid {0}." +INVALID_KUBERNETES_NAME_HELP = "Parameter {0} can only contain lowercase alphanumeric characters and hyphens" + +DUPLICATE_KUSTOMIZATION_NAME_ERROR = "Error! Invalid Kustomization list. Kustomization name {0} duplicated in multiple Kustomization objects" +DUPLICATE_KUSTOMIZATION_NAME_HELP = "Ensure that all Kustomization names are unique and try again" + +SSH_PRIVATE_KEY_WITH_HTTP_URL_ERROR = "Error! An --ssh-private-key cannot be used with an http(s) url" +SSH_PRIVATE_KEY_WITH_HTTP_URL_HELP = "Verify the url provided is a valid ssh url and not an http(s) url" + +KNOWN_HOSTS_WITH_HTTP_URL_ERROR = "Error! --ssh-known-hosts cannot be used with an http(s) url" +KNOWN_HOSTS_WITH_HTTP_URL_HELP = "Verify the url provided is a valid ssh url and not an http(s) url" + +HTTPS_AUTH_WITH_SSH_URL_ERROR = "Error! https auth (--https-user and --https-key) cannot be used with a non-http(s) url" +HTTPS_AUTH_WITH_SSH_URL_HELP = "Verify the url provided is a valid http(s) url and not an ssh url" + +KNOWN_HOSTS_BASE64_ENCODING_ERROR = "Error! ssh known_hosts is not a valid utf-8 base64 encoded string" +KNOWN_HOSTS_BASE64_ENCODING_HELP = "Verify that the string provided safely decodes into a valid utf-8 format" + +KNOWN_HOSTS_FORMAT_ERROR = "Error! ssh known_hosts provided in wrong format" +KNOWN_HOSTS_FORMAT_HELP = "Verify that all lines in the known_hosts contents are provided in a valid sshd(8) format" + +SSH_PRIVATE_KEY_ERROR = "Error! --ssh-private-key provided in invalid format" +SSH_PRIVATE_KEY_HELP = "Verify the key provided is a valid PEM-formatted key of type RSA, ECC, DSA, or Ed25519" + +HTTPS_USER_WITHOUT_KEY_ERROR = "Error! --https-user used without --https-key" +HTTPS_USER_WITHOUT_KEY_HELP = "Try providing both --https-user and --https-key together" + +HTTPS_KEY_WITHOUT_USER_ERROR = "Error! --http-key used without --http-user" +HTTPS_KEY_WITHOUT_USER_HELP = "Try providing both --https-user and --https-key together" + +KEY_FILE_READ_ERROR = "Error! Unable to read key file specified with: {0}" +KEY_FILE_READ_HELP = "Verify that the filepath specified exists and contains valid utf-8 data" + +KEY_AND_FILE_TOGETHER_ERROR = "Error! Both textual key and key filepath cannot be provided" +KEY_AND_FILE_TOGETHER_HELP = "Try providing the file parameter without providing the plaintext parameter" + +CC_REGISTRATION_WARNING = "'Flux Configuration' cannot be used because '{0}' provider has not been registered. More details for registering this provider can be found here - {1}" +CC_REGISTRATION_LINK = "https://aka.ms/RegisterKubernetesConfigurationProvider" +CC_REGISTRATION_ERROR = "Unable to fetch registration state of '{0}' provider. Failed to enable 'flux configuration' feature..." +CC_PROVIDER_NAMESPACE = 'Microsoft.KubernetesConfiguration' +REGISTERED = "Registered" + +HTTP_URL_NO_AUTH_WARNING = "Warning! https url is being used without https auth params, ensure the repository url provided is not a private repo" + + +DEPENDENCY_KEYS = ["dependencies", "depends_on"] +SYNC_INTERVAL_KEYS = ["interval", "sync_interval"] +TIMEOUT_KEY = "timeout" +SSH_PRIVATE_KEY_KEY = "sshPrivateKey" +REQUIRED_KUSTOMIZATION_KEYS = {"name", "path"} + +VALID_ISO8601_DURATION_REGEX = r"^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$" +VALID_URL_REGEX = r"^(((http|https|ssh)://)|(git@))" +VALID_KUBERNETES_NAME_REGEX = r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" + +GIT_CLI_KIND = "git" +GIT_DP_KIND = "GitRepository" + +CONNECTED_CLUSTERS = "connectedclusters" + +MANAGED_RP_NAMESPACE = "Microsoft.ContainerService" +CONNECTED_RP_NAMESPACE = "Microsoft.Kubernetes" diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 9d147741497..c9aed9022c3 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -3,77 +3,192 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from knack.util import CLIError +from azure.cli.core.azclierror import ResourceNotFoundError +from azure.core.exceptions import HttpResponseError +from .utils import get_cluster_type, get_data_from_key_or_file, get_protected_settings +from .validators import ( + validate_cc_registration, + validate_known_hosts, + validate_repository_ref, + validate_duration, + validate_git_repository, + validate_kustomization_list, + validate_private_key, + validate_url_with_params +) +from . import consts from .vendored_sdks.models import ( - FluxConfiguration, - GitRepositoryDefinition, - KustomizationDefinition, - RepositoryRefDefinition + FluxConfiguration, + GitRepositoryDefinition, + RepositoryRefDefinition, ) -from .utils import get_cluster_type -from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property -def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, - scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, - auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, - ssh_known_hosts=None, ssh_known_hosts_file=None): +def flux_config_show(client, resource_group_name, cluster_name, cluster_type, name): + """Get an existing Kubernetes Source Control Configuration. + """ # Determine ClusterRP cluster_rp = get_cluster_type(cluster_type) - repository_ref = RepositoryRefDefinition( - branch=branch, - tag=tag, - semver=semver, - commit=commit + try: + config = client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + print(config) + return config + except HttpResponseError as ex: + # Customize the error message for resources not found + if ex.response.status_code == 404: + # If Cluster not found + if ex.message.__contains__("(ResourceNotFound)"): + message = ex.message + recommendation = 'Verify that the --cluster-type is correct and the Resource ' \ + '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name) + # If Configuration not found + elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): + message = '(ConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \ + 'fluxConfigurations/{3} could not be found!'.format(cluster_rp, cluster_type, + cluster_name, name) + recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \ + '/fluxConfigurations/{3} exists'.format(cluster_rp, cluster_type, + cluster_name, name) + else: + message = ex.message + recommendation = '' + raise ResourceNotFoundError(message, recommendation) from ex + + +# pylint: disable=too-many-locals +def flux_config_create(cmd, client, resource_group_name, cluster_name, name, cluster_type, url=None, + scope='cluster', namespace='default', kind=consts.GIT_CLI_KIND, timeout=None, sync_interval=None, + branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, + ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + known_hosts_file=None, kustomization=None): + + # Pre-Validation + validate_repository_ref(branch, tag, semver, commit) + validate_duration("--timeout", timeout) + validate_duration("--sync-interval", sync_interval) + + if kustomization: + validate_kustomization_list(kustomization) + + # Get the protected settings and validate the private key value + protected_settings = get_protected_settings( + ssh_private_key, ssh_private_key_file, https_user, https_key ) + if consts.SSH_PRIVATE_KEY_KEY in protected_settings: + validate_private_key(protected_settings['sshPrivateKey']) + + # Get the known hosts data and validate it + knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file) + if knownhost_data: + validate_known_hosts(knownhost_data) + + # Validate registration with the RP endpoint + validate_cc_registration(cmd) + + git_repository = GitRepositoryDefinition() + dp_source_kind = consts.GIT_DP_KIND + + if kind == consts.GIT_CLI_KIND: + validate_git_repository(url) + validate_url_with_params(url, ssh_private_key, ssh_private_key_file, + known_hosts, known_hosts_file, https_user, https_key) + repository_ref = RepositoryRefDefinition( + branch=branch, + tag=tag, + semver=semver, + commit=commit + ) + git_repository = GitRepositoryDefinition( + url=url, + timeout=timeout, + sync_interval=sync_interval, + repository_ref=repository_ref, + ssh_known_hosts=knownhost_data, + https_user=https_user, + auth_ref_override=auth_ref_override + ) + + # Determine ClusterRP + cluster_rp = get_cluster_type(cluster_type) - git_repository = GitRepositoryDefinition( - url=url, - timeout=timeout, - sync_interval=sync_interval, - repository_ref=repository_ref, - ssh_known_hosts=ssh_known_hosts, - https_user=https_user, - auth_ref_override=auth_ref_override - ) - flux_configuration = FluxConfiguration( scope=scope, namespace=namespace, - source_kind=kind, + source_kind=dp_source_kind, timeout=timeout, sync_interval=sync_interval, git_repository=git_repository, - kustomizations=[] + kustomizations=kustomization ) - # cache the payload if --defer used or send to Azure - return cached_put(cmd, client.create_or_update, resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) -def flux_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, - dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): - - # Determine ClusterRP + return client.begin_create_or_update(resource_group_name, cluster_rp, + cluster_type, cluster_name, name, flux_configuration) + + +def flux_config_delete(client, resource_group_name, cluster_name, cluster_type, name): cluster_rp = get_cluster_type(cluster_type) + return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) - flux_configuration = cached_get(cmd, client.get, resource_group_name, cluster_rp, cluster_type, cluster_name, config_name) - kustomization = KustomizationDefinition( - name=name, - path=path, - dependencies=dependencies, - timeout=timeout, - sync_interval=sync_interval, - retry_interval=retry_interval, - prune=prune, - validation=validation, - force=force - ) +# def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, +# scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, +# auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, +# ssh_known_hosts=None, ssh_known_hosts_file=None): + +# # Determine ClusterRP +# cluster_rp = get_cluster_type(cluster_type) + +# repository_ref = RepositoryRefDefinition( +# branch=branch, +# tag=tag, +# semver=semver, +# commit=commit +# ) + +# git_repository = GitRepositoryDefinition( +# url=url, +# timeout=timeout, +# sync_interval=sync_interval, +# repository_ref=repository_ref, +# ssh_known_hosts=ssh_known_hosts, +# https_user=https_user, +# auth_ref_override=auth_ref_override +# ) + +# flux_configuration = FluxConfiguration( +# scope=scope, +# namespace=namespace, +# source_kind=kind, +# timeout=timeout, +# sync_interval=sync_interval, +# git_repository=git_repository, +# kustomizations=[] +# ) +# # cache the payload if --defer used or send to Azure +# return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, name, cluster_rp, cluster_type, cluster_name) + +# def flux_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, +# dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): + +# # Determine ClusterRP +# cluster_rp = get_cluster_type(cluster_type) + +# flux_configuration = cached_get(cmd, client.get, resource_group_name, cluster_rp, cluster_type, cluster_name, config_name) - upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') - flux_configuration = cached_put(cmd, client.create_or_update, resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration).result() - return get_property(flux_configuration.kustomizations, name) +# kustomization = KustomizationDefinition( +# name=name, +# path=path, +# dependencies=dependencies, +# timeout=timeout, +# sync_interval=sync_interval, +# retry_interval=retry_interval, +# prune=prune, +# validation=validation, +# force=force +# ) -def flux_delete(client, resource_group_name, cluster_name, name, cluster_type): - raise CLIError('TODO: Implement `k8s-config create`') +# upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') +# flux_configuration = cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, name).result() +# return get_property(flux_configuration.kustomizations, name) diff --git a/src/k8s-config/azext_k8s_config/tests/__init__.py b/src/k8s-config/azext_k8s_config/tests/__init__.py index 2dcf9bb68b3..99c0f28cd71 100644 --- a/src/k8s-config/azext_k8s_config/tests/__init__.py +++ b/src/k8s-config/azext_k8s_config/tests/__init__.py @@ -2,4 +2,4 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -# ----------------------------------------------------------------------------- \ No newline at end of file +# ----------------------------------------------------------------------------- diff --git a/src/k8s-config/azext_k8s_config/tests/latest/__init__.py b/src/k8s-config/azext_k8s_config/tests/latest/__init__.py index 2dcf9bb68b3..99c0f28cd71 100644 --- a/src/k8s-config/azext_k8s_config/tests/latest/__init__.py +++ b/src/k8s-config/azext_k8s_config/tests/latest/__init__.py @@ -2,4 +2,4 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -# ----------------------------------------------------------------------------- \ No newline at end of file +# ----------------------------------------------------------------------------- diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py index bfca0cc60b8..f3b125c8565 100644 --- a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py @@ -13,28 +13,8 @@ TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) -class K8s-configScenarioTest(ScenarioTest): +class K8sConfigScenarioTest(ScenarioTest): @ResourceGroupPreparer(name_prefix='cli_test_k8s-config') - def test_k8s-config(self, resource_group): - - self.kwargs.update({ - 'name': 'test1' - }) - - self.cmd('k8s-config create -g {rg} -n {name} --tags foo=doo', checks=[ - self.check('tags.foo', 'doo'), - self.check('name', '{name}') - ]) - self.cmd('k8s-config update -g {rg} -n {name} --tags foo=boo', checks=[ - self.check('tags.foo', 'boo') - ]) - count = len(self.cmd('k8s-config list').get_output_in_json()) - self.cmd('k8s-config show - {rg} -n {name}', checks=[ - self.check('name', '{name}'), - self.check('resourceGroup', '{rg}'), - self.check('tags.foo', 'boo') - ]) - self.cmd('k8s-config delete -g {rg} -n {name}') - final_count = len(self.cmd('k8s-config list').get_output_in_json()) - self.assertTrue(final_count, count - 1) \ No newline at end of file + def test_k8s_config(self, resource_group): + pass diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 73e8c579365..cdb4eb2233b 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -3,8 +3,86 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +import base64 +from azure.cli.core.azclierror import ( + MutuallyExclusiveArgumentError, + InvalidArgumentValueError, + RequiredArgumentMissingError +) +from . import consts + + def get_cluster_type(cluster_type): - if cluster_type.lower() == 'connectedclusters': - return 'Microsoft.Kubernetes' + if cluster_type.lower() == consts.CONNECTED_CLUSTERS: + return consts.CONNECTED_RP_NAMESPACE # Since cluster_type is an enum of only two values, if not connectedClusters, it will be managedClusters. - return 'Microsoft.ContainerService' \ No newline at end of file + return consts.MANAGED_RP_NAMESPACE + + +def get_data_from_key_or_file(key, filepath): + if key != '' and filepath != '': + raise MutuallyExclusiveArgumentError( + consts.KEY_AND_FILE_TOGETHER_ERROR, + consts.KEY_AND_FILE_TOGETHER_HELP) + data = '' + if filepath != '': + data = read_key_file(filepath) + elif key != '': + data = key + return data + + +def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key): + protected_settings = {} + ssh_private_key_data = get_data_from_key_or_file(ssh_private_key, ssh_private_key_file) + + # Add gitops private key data to protected settings if exists + # Dry-run all key types to determine if the private key is in a valid format + if ssh_private_key_data != '': + protected_settings[consts.SSH_PRIVATE_KEY_KEY] = ssh_private_key_data + + # Check if both httpsUser and httpsKey exist, then add to protected settings + if https_user != '' and https_key != '': + protected_settings[consts.HTTPS_USER_KEY] = to_base64(https_user) + protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key) + elif https_user != '': + raise RequiredArgumentMissingError( + consts.HTTPS_USER_WITHOUT_KEY_ERROR, + consts.HTTPS_USER_WITHOUT_KEY_HELP) + elif https_key != '': + raise RequiredArgumentMissingError( + consts.HTTPS_KEY_WITHOUT_USER_ERROR, + consts.HTTPS_KEY_WITHOUT_USER_HELP) + + return protected_settings + + +def read_key_file(path): + try: + with open(path, "r") as myfile: # user passed in filename + data_list = myfile.readlines() # keeps newline characters intact + data_list_len = len(data_list) + if (data_list_len) <= 0: + raise Exception("File provided does not contain any data") + raw_data = ''.join(data_list) + return to_base64(raw_data) + except Exception as ex: + raise InvalidArgumentValueError( + consts.KEY_FILE_READ_ERROR.format(ex), + consts.KEY_FILE_READ_HELP) from ex + + +def parse_dependencies(depends_on): + depends_on = depends_on.strip() + if depends_on[0] == '[': + depends_on = depends_on[1:-1] + return depends_on.split(',') + + +def from_base64(base64_str): + return base64.b64decode(base64_str) + + +def to_base64(raw_data): + bytes_data = raw_data.encode('utf-8') + return base64.b64encode(bytes_data).decode('utf-8') diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py new file mode 100644 index 00000000000..4c9730189f3 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -0,0 +1,207 @@ +# -------------------------------------------------------------------------------------------- +# 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 io +from urllib.parse import urlparse +from knack.log import get_logger +from azure.cli.core.azclierror import ( + InvalidArgumentValueError, + RequiredArgumentMissingError, + MutuallyExclusiveArgumentError +) +from paramiko.hostkeys import HostKeyEntry +from paramiko.ed25519key import Ed25519Key +from paramiko.ssh_exception import SSHException +from Crypto.PublicKey import RSA, ECC, DSA + +from .utils import from_base64 +from ._client_factory import resource_providers_client +from . import consts + + +logger = get_logger(__name__) + + +def validate_namespace(namespace): + if namespace.namespace: + __validate_k8s_name(namespace.namespace, "--namespace", 23) + + +def validate_operator_instance_name(namespace): + if namespace.operator_instance_name: + __validate_k8s_name(namespace.operator_instance_name, "--operator-instance-name", 23) + + +def validate_configuration_name(namespace): + __validate_k8s_name(namespace.name, "--name", 63) + + +def validate_kustomization(values): + required_keys = consts.REQUIRED_KUSTOMIZATION_KEYS + for item in values: + key, value = item.split('=', 1) + if key == "name": + __validate_k8s_name(value, key, 63) + elif key == consts.SYNC_INTERVAL_KEYS: + validate_duration("interval", value) + elif key == consts.TIMEOUT_KEY: + validate_duration("timeout", value) + if key in required_keys: + required_keys.remove(key) + if required_keys: + raise RequiredArgumentMissingError( + consts.KUSTOMIZATION_REQUIRED_VALUES_MISSING_ERROR.format(required_keys), + consts.KUSTOMIZATION_REQUIRED_VALUES_MISSING_HELP + ) + + +def validate_kustomization_list(kustomizations): + kustomization_names = set() + for kustomization in kustomizations: + if kustomization.name in kustomization_names: + raise InvalidArgumentValueError( + consts.DUPLICATE_KUSTOMIZATION_NAME_ERROR.format(kustomization.name), + consts.DUPLICATE_KUSTOMIZATION_NAME_HELP + ) + kustomization_names.add(kustomization.name) + + +def validate_repository_ref(branch: str, tag: str, semver: str, commit: str): + if not branch and not tag and not semver and not commit: + raise RequiredArgumentMissingError( + consts.REPOSITORY_REF_REQUIRED_VALUES_MISSING_ERROR, + consts.REPOSITORY_REF_REQUIRED_VALUES_MISSING_HELP + ) + + +def validate_duration(arg_name: str, duration: str): + if duration and not re.match(consts.VALID_ISO8601_DURATION_REGEX, duration): + raise InvalidArgumentValueError( + consts.INVALID_DURATION_ERROR.format(arg_name), + consts.INVALID_DURATION_HELP + ) + + +def validate_git_repository(url: str): + if not url: + raise RequiredArgumentMissingError( + consts.GIT_REPOSITORY_REQUIRED_VALUES_MISSING_ERROR.format("--url"), + consts.GIT_REPOSITORY_REQUIRED_VALUES_MISSING_HELP + ) + validate_git_url(url) + + +def validate_git_url(url: str): + if not re.match(consts.VALID_URL_REGEX, url): + raise InvalidArgumentValueError( + consts.INVALID_URL_ERROR, + consts.INVALID_URL_HELP + ) + + +# Helper +def __validate_k8s_name(param_value, param_name, max_len): + if len(param_value) > max_len: + raise InvalidArgumentValueError( + consts.INVALID_KUBERNETES_NAME_LENGTH_ERROR.format(param_name), + consts.INVALID_KUBERNETES_NAME_LENGTH_HELP.format(param_name, max_len) + ) + if not re.match(consts.VALID_KUBERNETES_NAME_REGEX, param_value): + if param_value[0] == "-" or param_value[-1] == "-": + raise InvalidArgumentValueError( + consts.INVALID_KUBERNETES_NAME_HYPHEN_ERROR.format(param_name), + consts.INVALID_KUBERNETES_NAME_HYPHEN_HELP.format(param_name) + ) + raise InvalidArgumentValueError( + consts.INVALID_KUBERNETES_NAME_ERROR.format(param_name), + consts.INVALID_KUBERNETES_NAME_HELP.format(param_name) + ) + + +def validate_url_with_params(url: str, ssh_private_key, ssh_private_key_file, + known_hosts, known_hosts_file, https_user, https_key): + + scheme = urlparse(url).scheme + + if scheme.lower() in ('http', 'https'): + if ssh_private_key or ssh_private_key_file: + raise MutuallyExclusiveArgumentError( + consts.SSH_PRIVATE_KEY_WITH_HTTP_URL_ERROR, + consts.SSH_PRIVATE_KEY_WITH_HTTP_URL_HELP + ) + if known_hosts or known_hosts_file: + raise MutuallyExclusiveArgumentError( + consts.KNOWN_HOSTS_WITH_HTTP_URL_ERROR, + consts.KNOWN_HOSTS_WITH_HTTP_URL_HELP + ) + if not (https_user and https_key) and scheme == 'https': + logger.warning(consts.HTTP_URL_NO_AUTH_WARNING) + else: + if https_user and https_key: + raise MutuallyExclusiveArgumentError( + consts.HTTPS_AUTH_WITH_SSH_URL_ERROR, + consts.HTTPS_AUTH_WITH_SSH_URL_HELP + ) + + +def validate_known_hosts(knownhost_data): + try: + knownhost_str = from_base64(knownhost_data).decode('utf-8') + except Exception as ex: + raise InvalidArgumentValueError( + consts.SSH_BASE64_ENCODING_ERROR, + consts.SSH_BASE64_ENCODING_HELP) from ex + lines = knownhost_str.split('\n') + for line in lines: + line = line.strip(' ') + line_len = len(line) + if (line_len == 0) or (line[0] == "#"): + continue + try: + host_key = HostKeyEntry.from_line(line) + if not host_key: + raise Exception('not enough fields found in known_hosts line') + except Exception as ex: + raise InvalidArgumentValueError( + consts.KNOWN_HOSTS_FORMAT_ERROR, + consts.KNOWN_HOSTS_FORMAT_HELP + ) from ex + + +def validate_private_key(ssh_private_key_data): + try: + RSA.import_key(from_base64(ssh_private_key_data)) + return + except ValueError: + try: + ECC.import_key(from_base64(ssh_private_key_data)) + return + except ValueError: + try: + DSA.import_key(from_base64(ssh_private_key_data)) + return + except ValueError: + try: + key_obj = io.StringIO(from_base64(ssh_private_key_data).decode('utf-8')) + Ed25519Key(file_obj=key_obj) + return + except SSHException: + raise InvalidArgumentValueError( + consts.SSH_PRIVATE_KEY_ERROR, + consts.SSH_PRIVATE_KEY_HELP + ) + + +# pylint: disable=broad-except +def validate_cc_registration(cmd): + try: + rp_client = resource_providers_client(cmd.cli_ctx) + registration_state = rp_client.get(consts.CC_PROVIDER_NAMESPACE).registration_state + + if registration_state.lower() != consts.REGISTERED.lower(): + logger.warning(consts.CC_REGISTRATION_WARNING.format(consts.CC_PROVIDER_NAMESPACE, consts.CC_REGISTRATION_LINK)) + except Exception: + logger.warning(consts.CC_REGISTRATION_ERROR.format(consts.CC_PROVIDER_NAMESPACE)) diff --git a/src/k8s-config/setup.py b/src/k8s-config/setup.py index 912117037d8..073813e5e8b 100644 --- a/src/k8s-config/setup.py +++ b/src/k8s-config/setup.py @@ -57,4 +57,4 @@ packages=find_packages(), install_requires=DEPENDENCIES, package_data={'azext_k8s-config': ['azext_metadata.json']}, -) \ No newline at end of file +) From b75b84fce5c5b868f9e06f69a8382f58d09e9848 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 2 Jun 2021 15:08:58 -0700 Subject: [PATCH 04/61] Add help text to commands, params --- src/k8s-config/HISTORY.rst | 3 +- src/k8s-config/azext_k8s_config/_help.py | 39 +++++++++++++-- src/k8s-config/azext_k8s_config/_params.py | 55 ++++++++++++---------- src/k8s-config/azext_k8s_config/consts.py | 13 +++-- 4 files changed, 76 insertions(+), 34 deletions(-) diff --git a/src/k8s-config/HISTORY.rst b/src/k8s-config/HISTORY.rst index 8c34bccfff8..13b4a515dad 100644 --- a/src/k8s-config/HISTORY.rst +++ b/src/k8s-config/HISTORY.rst @@ -5,4 +5,5 @@ Release History 0.1.0 ++++++ -* Initial release. \ No newline at end of file + +* Release k8s-config with flux configuration support \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 5f70be8f1fd..0ecf5db84d4 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -9,25 +9,54 @@ helps['k8s-config'] = """ type: group - short-summary: Commands to manage K8s-configs. + short-summary: Commands to manage resources from Microsoft.KubernetesConfiguration. """ helps['k8s-config flux create'] = """ type: command - short-summary: Create a K8s-config. + short-summary: Create a Kubernetes Flux Configuration. + examples: + - name: Create a Kubernetes Flux Configuration + text: |- + az k8s-config flux create --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ + --kind git --url https://github.com/Azure/arc-k8s-demo --branch main --kustomization \\ + name=my-kustomization path="./apps" + - name: Create a Kubernetes Flux Configuration with Multiple Kustomizations + text: |- + az k8s-config flux create --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ + --kind git --url https://github.com/Azure/arc-k8s-demo --https-user my-username \\ + --https-key my-password --branch main --kustomization name=my-crds path="./crds" \\ + --kustomization name=my-apps path="./apps" depends_on=my-crds timeout=PT5M """ helps['k8s-config flux list'] = """ type: command - short-summary: List K8s-configs. + short-summary: List Kubernetes Flux Configurations. + examples: + - name: List all Kubernetes Flux Configurations on a cluster + text: |- + az k8s-config flux list --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters """ helps['k8s-config flux show'] = """ type: command - short-summary: List K8s-configs. + short-summary: Show a Kubernetes Flux Configuration. + examples: + - name: Show details of a Kubernetes Flux Configuration + text: |- + az k8s-config flux show --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myconfig """ helps['k8s-config flux delete'] = """ type: command - short-summary: List K8s-configs. + short-summary: Delete a Kubernetes Flux Configuration. + examples: + - name: Delete an existing Kubernetes Flux Configuration + text: |- + az k8s-config flux delete --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myconfig """ diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 722ce14dd31..e121ec64b04 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -29,64 +29,69 @@ def load_arguments(self, _): options_list=['--cluster-name', '-c'], help='Name of the Kubernetes cluster') c.argument('cluster_type', + options_list=['--cluster-type', '-t'], arg_type=get_enum_type(['connectedClusters', 'managedClusters']), - help='Specify Arc clusters or AKS managed clusters.') + help='Specify Arc connected clusters or AKS managed clusters.') with self.argument_context('k8s-config flux create') as c: - c.argument('kustomization', - options_list=['--kustomization', '-k'], - action=KustomizationAddAction, - nargs='+') c.argument('scope', + options_list=['--scope', '-s'], arg_type=get_enum_type(['namespace', 'cluster']), help="Specify scope of the operator to be 'namespace' or 'cluster'") c.argument('namespace', - help='Specify namespace to deploy the configuration', + help='Namespace to deploy the configuration', + options_list=['--namespace', '--ns'], validator=validate_namespace) c.argument('kind', arg_type=get_enum_type([GIT_CLI_KIND]), - help='Specify the source kind to reconcile') + help='Source kind to reconcile') c.argument('url', options_list=['--url', '-u'], - help='Specify namespace to deploy the configuration') + help='URL of the source to reconcile') c.argument('timeout', - help='Specify the source kind to reconcile') + help='Maximum time to reconcile the source before timing out') c.argument('sync_interval', options_list=['--interval', '--sync-interval'], - help='Specify the source kind to reconcile') + help='Time between reconciliations of the source on the cluster') c.argument('branch', arg_group="Repo Ref", - help='Specify the branch to reconcile the git repository source kind') + help='Branch to reconcile with the git source') c.argument('tag', arg_group="Repo Ref", - help='Specify the branch to reconcile the git repository source kind') + help='Tag to reconcile with the git source') c.argument('semver', arg_group="Repo Ref", - help='Specify the branch to reconcile the git repository source kind') + help='Semver range to reconcile with the git source') c.argument('commit', arg_group="Repo Ref", - help='Specify the branch to reconcile the git repository source kind') - c.argument('auth_ref_override', - options_list=['--auth-ref-override', '--auth-ref'], - help='Specify the branch to reconcile the git repository source kind') + help='Specific commit to reconcile with the git source') c.argument('ssh_private_key', arg_group="Auth", - help='Specify Base64-encoded private ssh key for private repository sync') + help='Base64-encoded private ssh key for private repository sync') c.argument('ssh_private_key_file', arg_group="Auth", - help='Specify filepath to private ssh key for private repository sync') + help='Filepath to private ssh key for private repository sync') c.argument('https_user', arg_group="Auth", - help='Specify HTTPS username for private repository sync') + help='HTTPS username for private repository sync') c.argument('https_key', arg_group="Auth", - help='Specify HTTPS token/password for private repository sync') - c.argument('ssh_known_hosts', + help='HTTPS token/password for private repository sync') + c.argument('known_hosts', arg_group="Auth", - help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') - c.argument('ssh_known_hosts_file', + help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') + c.argument('known_hosts_file', arg_group="Auth", - help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') + help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') + c.argument('auth_ref_override', + options_list=['--auth-ref-override'], + arg_group="Auth", + help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') + c.argument('kustomization', + options_list=['--kustomization', '-k'], + action=KustomizationAddAction, + help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", + nargs='+') # with self.argument_context('k8s-config flux source') as c: # c.argument('scope', diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index c95e8c4cd17..693578cba06 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -5,6 +5,8 @@ # pylint: disable=line-too-long +# ERROR/HELP TEXT DEFINITIONS ----------------------------------------- + KUSTOMIZATION_REQUIRED_VALUES_MISSING_ERROR = "Error! Kustomization definition is invalid, required values {} not found" KUSTOMIZATION_REQUIRED_VALUES_MISSING_HELP = "Add the required values to the Kustomization object and try again" @@ -62,19 +64,23 @@ KEY_AND_FILE_TOGETHER_ERROR = "Error! Both textual key and key filepath cannot be provided" KEY_AND_FILE_TOGETHER_HELP = "Try providing the file parameter without providing the plaintext parameter" +HTTP_URL_NO_AUTH_WARNING = "Warning! https url is being used without https auth params, ensure the repository url provided is not a private repo" + +# PROVIDER REGISTRATION ----------------------------------------- + CC_REGISTRATION_WARNING = "'Flux Configuration' cannot be used because '{0}' provider has not been registered. More details for registering this provider can be found here - {1}" CC_REGISTRATION_LINK = "https://aka.ms/RegisterKubernetesConfigurationProvider" CC_REGISTRATION_ERROR = "Unable to fetch registration state of '{0}' provider. Failed to enable 'flux configuration' feature..." CC_PROVIDER_NAMESPACE = 'Microsoft.KubernetesConfiguration' REGISTERED = "Registered" -HTTP_URL_NO_AUTH_WARNING = "Warning! https url is being used without https auth params, ensure the repository url provided is not a private repo" - +SSH_PRIVATE_KEY_KEY = "sshPrivateKey" +HTTPS_USER_KEY = "httpsUser" +HTTPS_KEY_KEY = "httpsKey" DEPENDENCY_KEYS = ["dependencies", "depends_on"] SYNC_INTERVAL_KEYS = ["interval", "sync_interval"] TIMEOUT_KEY = "timeout" -SSH_PRIVATE_KEY_KEY = "sshPrivateKey" REQUIRED_KUSTOMIZATION_KEYS = {"name", "path"} VALID_ISO8601_DURATION_REGEX = r"^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$" @@ -85,6 +91,7 @@ GIT_DP_KIND = "GitRepository" CONNECTED_CLUSTERS = "connectedclusters" +MANAGED_CLUSTERS = "managedclusters" MANAGED_RP_NAMESPACE = "Microsoft.ContainerService" CONNECTED_RP_NAMESPACE = "Microsoft.Kubernetes" From 06d0ef8438fd475da0f66e7275056cd5a36950cd Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 2 Jun 2021 15:12:25 -0700 Subject: [PATCH 05/61] Add other clients to client factory --- src/k8s-config/azext_k8s_config/_client_factory.py | 8 ++++++++ src/k8s-config/azext_k8s_config/_params.py | 6 ++---- src/k8s-config/azext_k8s_config/consts.py | 4 ++-- src/k8s-config/azext_k8s_config/custom.py | 6 +++--- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_client_factory.py b/src/k8s-config/azext_k8s_config/_client_factory.py index 27b5d6dfb39..92afaef212a 100644 --- a/src/k8s-config/azext_k8s_config/_client_factory.py +++ b/src/k8s-config/azext_k8s_config/_client_factory.py @@ -15,6 +15,14 @@ def k8s_config_fluxconfig_client(cli_ctx, _): return k8s_config_client(cli_ctx).flux_configurations +def k8s_config_sourcecontrol_client(cli_ctx, _): + return k8s_config_client(cli_ctx).source_control_configurations + + +def k8s_config_extension_client(cli_ctx, _): + return k8s_config_client(cli_ctx).extensions + + def resource_providers_client(cli_ctx): from azure.mgmt.resource import ResourceManagementClient return get_mgmt_service_client(cli_ctx, ResourceManagementClient).providers diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index e121ec64b04..d8f3f8637f3 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -12,9 +12,7 @@ ) from .validators import validate_configuration_name, validate_namespace from .action import KustomizationAddAction -from .consts import ( - GIT_CLI_KIND -) +from . import consts def load_arguments(self, _): @@ -43,7 +41,7 @@ def load_arguments(self, _): options_list=['--namespace', '--ns'], validator=validate_namespace) c.argument('kind', - arg_type=get_enum_type([GIT_CLI_KIND]), + arg_type=get_enum_type([consts.GIT]), help='Source kind to reconcile') c.argument('url', options_list=['--url', '-u'], diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 693578cba06..cbc2ee591b8 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -87,8 +87,8 @@ VALID_URL_REGEX = r"^(((http|https|ssh)://)|(git@))" VALID_KUBERNETES_NAME_REGEX = r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" -GIT_CLI_KIND = "git" -GIT_DP_KIND = "GitRepository" +GIT = "git" +GIT_REPOSITORY = "GitRepository" CONNECTED_CLUSTERS = "connectedclusters" MANAGED_CLUSTERS = "managedclusters" diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index c9aed9022c3..95e6002638f 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -59,7 +59,7 @@ def flux_config_show(client, resource_group_name, cluster_name, cluster_type, na # pylint: disable=too-many-locals def flux_config_create(cmd, client, resource_group_name, cluster_name, name, cluster_type, url=None, - scope='cluster', namespace='default', kind=consts.GIT_CLI_KIND, timeout=None, sync_interval=None, + scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): @@ -88,9 +88,9 @@ def flux_config_create(cmd, client, resource_group_name, cluster_name, name, clu validate_cc_registration(cmd) git_repository = GitRepositoryDefinition() - dp_source_kind = consts.GIT_DP_KIND + dp_source_kind = consts.GIT_REPOSITORY - if kind == consts.GIT_CLI_KIND: + if kind == consts.GIT: validate_git_repository(url) validate_url_with_params(url, ssh_private_key, ssh_private_key_file, known_hosts, known_hosts_file, https_user, https_key) From da0684dfa7021758b99e35700936bf34ec0725fc Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 3 Jun 2021 09:19:37 -0700 Subject: [PATCH 06/61] Automatically installing the flux extension --- .../azext_k8s_config/_client_factory.py | 6 ++-- src/k8s-config/azext_k8s_config/consts.py | 5 +++ src/k8s-config/azext_k8s_config/custom.py | 33 ++++++++++++++++--- 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_client_factory.py b/src/k8s-config/azext_k8s_config/_client_factory.py index 92afaef212a..08144419b0a 100644 --- a/src/k8s-config/azext_k8s_config/_client_factory.py +++ b/src/k8s-config/azext_k8s_config/_client_factory.py @@ -11,15 +11,15 @@ def k8s_config_client(cli_ctx, *_): return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient) -def k8s_config_fluxconfig_client(cli_ctx, _): +def k8s_config_fluxconfig_client(cli_ctx, *_): return k8s_config_client(cli_ctx).flux_configurations -def k8s_config_sourcecontrol_client(cli_ctx, _): +def k8s_config_sourcecontrol_client(cli_ctx, *_): return k8s_config_client(cli_ctx).source_control_configurations -def k8s_config_extension_client(cli_ctx, _): +def k8s_config_extension_client(cli_ctx, *_): return k8s_config_client(cli_ctx).extensions diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index cbc2ee591b8..ab570b0bcfd 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -64,6 +64,9 @@ KEY_AND_FILE_TOGETHER_ERROR = "Error! Both textual key and key filepath cannot be provided" KEY_AND_FILE_TOGETHER_HELP = "Try providing the file parameter without providing the plaintext parameter" +SCC_EXISTS_ON_CLUSTER_ERROR = "Error! SourceControlConfigurations with flux already exist on the cluster" +SCC_EXISTS_ON_CLUSTER_HELP = "Try removing all sourceControlConfigurations from the cluster before attempting to add fluxConfigurations" + HTTP_URL_NO_AUTH_WARNING = "Warning! https url is being used without https auth params, ensure the repository url provided is not a private repo" # PROVIDER REGISTRATION ----------------------------------------- @@ -74,6 +77,8 @@ CC_PROVIDER_NAMESPACE = 'Microsoft.KubernetesConfiguration' REGISTERED = "Registered" +FLUX_EXTENSION_TYPE = "microsoft.flux" + SSH_PRIVATE_KEY_KEY = "sshPrivateKey" HTTPS_USER_KEY = "httpsUser" HTTPS_KEY_KEY = "httpsKey" diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 95e6002638f..39a5581f204 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -3,8 +3,12 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from azure.cli.core.azclierror import ResourceNotFoundError +from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.core.exceptions import HttpResponseError +from ._client_factory import ( + k8s_config_sourcecontrol_client, + k8s_config_extension_client +) from .utils import get_cluster_type, get_data_from_key_or_file, get_protected_settings from .validators import ( validate_cc_registration, @@ -33,7 +37,6 @@ def flux_config_show(client, resource_group_name, cluster_name, cluster_type, na try: config = client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name) - print(config) return config except HttpResponseError as ex: # Customize the error message for resources not found @@ -64,6 +67,9 @@ def flux_config_create(cmd, client, resource_group_name, cluster_name, name, clu ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): + # Determine ClusterRP + cluster_rp = get_cluster_type(cluster_type) + # Pre-Validation validate_repository_ref(branch, tag, semver, commit) validate_duration("--timeout", timeout) @@ -72,6 +78,26 @@ def flux_config_create(cmd, client, resource_group_name, cluster_name, name, clu if kustomization: validate_kustomization_list(kustomization) + # Validate if we are able to install the flux configuration + scc_client = k8s_config_sourcecontrol_client(cmd.cli_ctx) + configs = scc_client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) + # configs is an iterable, no len() so we have to iterate to check for configs + for _ in configs: + raise DeploymentError( + consts.SCC_EXISTS_ON_CLUSTER_ERROR, + consts.SCC_EXISTS_ON_CLUSTER_HELP) + + # Validate if the extension is installed, if not, install it + extension_client = k8s_config_extension_client(cmd.cli_ctx) + extensions = extension_client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) + found_flux_extension = False + for extension in extensions: + if extension.extension_type.lower() == consts.FLUX_EXTENSION_TYPE: + found_flux_extension = True + break + if not found_flux_extension: + print("We should install the flux extension automatically here") + # Get the protected settings and validate the private key value protected_settings = get_protected_settings( ssh_private_key, ssh_private_key_file, https_user, https_key @@ -110,9 +136,6 @@ def flux_config_create(cmd, client, resource_group_name, cluster_name, name, clu auth_ref_override=auth_ref_override ) - # Determine ClusterRP - cluster_rp = get_cluster_type(cluster_type) - flux_configuration = FluxConfiguration( scope=scope, namespace=namespace, From d32a451cd2771e45d6faa0090883668b7643bf8b Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 3 Jun 2021 13:41:16 -0700 Subject: [PATCH 07/61] Move flux and extension into modules --- .../azext_k8s_config/_client_factory.py | 16 + src/k8s-config/azext_k8s_config/custom.py | 151 +----- .../partner_extensions/AzureDefender.py | 60 +++ .../partner_extensions/AzureMLKubernetes.py | 428 +++++++++++++++++ .../partner_extensions/Cassandra.py | 45 ++ .../partner_extensions/ContainerInsights.py | 447 ++++++++++++++++++ .../partner_extensions/DefaultExtension.py | 46 ++ .../PartnerExtensionModel.py | 22 + .../partner_extensions/__init__.py | 5 + .../providers/ExtensionProvider.py | 176 +++++++ .../providers/FluxConfigurationProvider.py | 163 +++++++ .../azext_k8s_config/providers/__init__.py | 0 src/k8s-config/azext_k8s_config/utils.py | 17 +- 13 files changed, 1439 insertions(+), 137 deletions(-) create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py create mode 100644 src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py create mode 100644 src/k8s-config/azext_k8s_config/providers/__init__.py diff --git a/src/k8s-config/azext_k8s_config/_client_factory.py b/src/k8s-config/azext_k8s_config/_client_factory.py index 08144419b0a..f051ed7841b 100644 --- a/src/k8s-config/azext_k8s_config/_client_factory.py +++ b/src/k8s-config/azext_k8s_config/_client_factory.py @@ -4,6 +4,7 @@ # -------------------------------------------------------------------------------------------- from azure.cli.core.commands.client_factory import get_mgmt_service_client +from azure.cli.core.profiles import ResourceType def k8s_config_client(cli_ctx, *_): @@ -26,3 +27,18 @@ def k8s_config_extension_client(cli_ctx, *_): def resource_providers_client(cli_ctx): from azure.mgmt.resource import ResourceManagementClient return get_mgmt_service_client(cli_ctx, ResourceManagementClient).providers + + +def cf_resource_groups(cli_ctx, subscription_id=None): + return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, + subscription_id=subscription_id).resource_groups + + +def cf_resources(cli_ctx, subscription_id=None): + return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, + subscription_id=subscription_id).resources + + +def cf_log_analytics(cli_ctx, subscription_id=None): + from azure.mgmt.loganalytics import LogAnalyticsManagementClient # pylint: disable=no-name-in-module + return get_mgmt_service_client(cli_ctx, LogAnalyticsManagementClient, subscription_id=subscription_id) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 39a5581f204..c4228fc0e07 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -3,61 +3,16 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError -from azure.core.exceptions import HttpResponseError -from ._client_factory import ( - k8s_config_sourcecontrol_client, - k8s_config_extension_client -) -from .utils import get_cluster_type, get_data_from_key_or_file, get_protected_settings -from .validators import ( - validate_cc_registration, - validate_known_hosts, - validate_repository_ref, - validate_duration, - validate_git_repository, - validate_kustomization_list, - validate_private_key, - validate_url_with_params -) +from .providers.ExtensionProvider import ExtensionProvider +from .providers.FluxConfigurationProvider import FluxConfigurationProvider from . import consts -from .vendored_sdks.models import ( - FluxConfiguration, - GitRepositoryDefinition, - RepositoryRefDefinition, -) - -def flux_config_show(client, resource_group_name, cluster_name, cluster_type, name): +def flux_config_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): """Get an existing Kubernetes Source Control Configuration. """ - # Determine ClusterRP - cluster_rp = get_cluster_type(cluster_type) - - try: - config = client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name) - return config - except HttpResponseError as ex: - # Customize the error message for resources not found - if ex.response.status_code == 404: - # If Cluster not found - if ex.message.__contains__("(ResourceNotFound)"): - message = ex.message - recommendation = 'Verify that the --cluster-type is correct and the Resource ' \ - '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name) - # If Configuration not found - elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): - message = '(ConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \ - 'fluxConfigurations/{3} could not be found!'.format(cluster_rp, cluster_type, - cluster_name, name) - recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \ - '/fluxConfigurations/{3} exists'.format(cluster_rp, cluster_type, - cluster_name, name) - else: - message = ex.message - recommendation = '' - raise ResourceNotFoundError(message, recommendation) from ex + provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) + return provider.show() # pylint: disable=too-many-locals @@ -67,92 +22,16 @@ def flux_config_create(cmd, client, resource_group_name, cluster_name, name, clu ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): - # Determine ClusterRP - cluster_rp = get_cluster_type(cluster_type) - - # Pre-Validation - validate_repository_ref(branch, tag, semver, commit) - validate_duration("--timeout", timeout) - validate_duration("--sync-interval", sync_interval) - - if kustomization: - validate_kustomization_list(kustomization) - - # Validate if we are able to install the flux configuration - scc_client = k8s_config_sourcecontrol_client(cmd.cli_ctx) - configs = scc_client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - # configs is an iterable, no len() so we have to iterate to check for configs - for _ in configs: - raise DeploymentError( - consts.SCC_EXISTS_ON_CLUSTER_ERROR, - consts.SCC_EXISTS_ON_CLUSTER_HELP) - - # Validate if the extension is installed, if not, install it - extension_client = k8s_config_extension_client(cmd.cli_ctx) - extensions = extension_client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - found_flux_extension = False - for extension in extensions: - if extension.extension_type.lower() == consts.FLUX_EXTENSION_TYPE: - found_flux_extension = True - break - if not found_flux_extension: - print("We should install the flux extension automatically here") - - # Get the protected settings and validate the private key value - protected_settings = get_protected_settings( - ssh_private_key, ssh_private_key_file, https_user, https_key - ) - if consts.SSH_PRIVATE_KEY_KEY in protected_settings: - validate_private_key(protected_settings['sshPrivateKey']) - - # Get the known hosts data and validate it - knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file) - if knownhost_data: - validate_known_hosts(knownhost_data) - - # Validate registration with the RP endpoint - validate_cc_registration(cmd) - - git_repository = GitRepositoryDefinition() - dp_source_kind = consts.GIT_REPOSITORY - - if kind == consts.GIT: - validate_git_repository(url) - validate_url_with_params(url, ssh_private_key, ssh_private_key_file, - known_hosts, known_hosts_file, https_user, https_key) - repository_ref = RepositoryRefDefinition( - branch=branch, - tag=tag, - semver=semver, - commit=commit - ) - git_repository = GitRepositoryDefinition( - url=url, - timeout=timeout, - sync_interval=sync_interval, - repository_ref=repository_ref, - ssh_known_hosts=knownhost_data, - https_user=https_user, - auth_ref_override=auth_ref_override - ) - - flux_configuration = FluxConfiguration( - scope=scope, - namespace=namespace, - source_kind=dp_source_kind, - timeout=timeout, - sync_interval=sync_interval, - git_repository=git_repository, - kustomizations=kustomization - ) - - return client.begin_create_or_update(resource_group_name, cluster_rp, - cluster_type, cluster_name, name, flux_configuration) - - -def flux_config_delete(client, resource_group_name, cluster_name, cluster_type, name): - cluster_rp = get_cluster_type(cluster_type) - return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, name, cluster_type) + return provider.create(url, scope, namespace, kind, timeout, sync_interval, + branch, tag, semver, commit, auth_ref_override, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, + known_hosts_file, kustomization) + + +def flux_config_delete(cmd, client, resource_group_name, cluster_name, cluster_type, name): + provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) + return provider.delete() # def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py b/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py new file mode 100644 index 00000000000..1496b7aad94 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py @@ -0,0 +1,60 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument + +from knack.log import get_logger + +from ..vendored_sdks.models import Extension +from ..vendored_sdks.models import ScopeCluster +from ..vendored_sdks.models import Scope + +from .PartnerExtensionModel import PartnerExtensionModel +from .ContainerInsights import _get_container_insights_settings + +logger = get_logger(__name__) + + +class AzureDefender(PartnerExtensionModel): + def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, + scope, auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file): + + """ExtensionType 'microsoft.azuredefender.kubernetes' specific validations & defaults for Create + Must create and return a valid 'ExtensionInstance' object. + + """ + # NOTE-1: Replace default scope creation with your customization! + ext_scope = None + # Hardcoding name, release_namespace and scope since ci only supports one instance and cluster scope + # and platform doesnt have support yet extension specific constraints like this + name = extension_type.lower() + release_namespace = "azuredefender" + # Scope is always cluster + scope_cluster = ScopeCluster(release_namespace=release_namespace) + ext_scope = Scope(cluster=scope_cluster, namespace=None) + + is_ci_extension_type = False + + logger.warning('Ignoring name, release-namespace and scope parameters since %s ' + 'only supports cluster scope and single instance of this extension.', extension_type) + logger.warning("Defaulting to extension name '%s' and release-namespace '%s'", name, release_namespace) + + _get_container_insights_settings(cmd, resource_group_name, cluster_name, configuration_settings, + configuration_protected_settings, is_ci_extension_type) + + # NOTE-2: Return a valid ExtensionInstance object, Instance name and flag for Identity + create_identity = True + extension_instance = Extension( + extension_type=extension_type, + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version, + scope=ext_scope, + configuration_settings=configuration_settings, + configuration_protected_settings=configuration_protected_settings + ) + return extension_instance, name, create_identity diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py new file mode 100644 index 00000000000..627e7feed3b --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py @@ -0,0 +1,428 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument +import copy +from hashlib import md5 +from typing import Any, Dict, List, Tuple + +import azure.mgmt.relay +import azure.mgmt.relay.models +import azure.mgmt.resource.locks +import azure.mgmt.servicebus +import azure.mgmt.servicebus.models +import azure.mgmt.storage +import azure.mgmt.storage.models +import azure.mgmt.loganalytics +import azure.mgmt.loganalytics.models +from ..vendored_sdks.models import ( + Extension, Scope, ScopeCluster) +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id +from azure.mgmt.resource.locks.models import ManagementLockObject +from knack.log import get_logger +from msrestazure.azure_exceptions import CloudError + +from .._client_factory import cf_resources +from .PartnerExtensionModel import PartnerExtensionModel + +logger = get_logger(__name__) + +resource_tag = {'created_by': 'amlk8s-extension'} + + +class AzureMLKubernetes(PartnerExtensionModel): + def __init__(self): + # constants for configuration settings. + self.DEFAULT_RELEASE_NAMESPACE = 'azureml' + self.RELAY_CONNECTION_STRING_KEY = 'relayserver.relayConnectionString' + self.RELAY_CONNECTION_STRING_DEPRECATED_KEY = 'RelayConnectionString' # for 3rd party deployment, will be deprecated + self.HC_RESOURCE_ID_KEY = 'relayserver.hybridConnectionResourceID' + self.RELAY_HC_NAME_KEY = 'relayserver.hybridConnectionName' + self.SERVICE_BUS_CONNECTION_STRING_KEY = 'servicebus.connectionString' + self.SERVICE_BUS_RESOURCE_ID_KEY = 'servicebus.resourceID' + self.SERVICE_BUS_TOPIC_SUB_MAPPING_KEY = 'servicebus.topicSubMapping' + self.AZURE_LOG_ANALYTICS_ENABLED_KEY = 'azure_log_analytics.enabled' + self.AZURE_LOG_ANALYTICS_CUSTOMER_ID_KEY = 'azure_log_analytics.customer_id' + self.AZURE_LOG_ANALYTICS_CONNECTION_STRING = 'azure_log_analytics.connection_string' + self.JOB_SCHEDULER_LOCATION_KEY = 'jobSchedulerLocation' + self.CLUSTER_NAME_FRIENDLY_KEY = 'cluster_name_friendly' + + # component flag + self.ENABLE_TRAINING = 'enableTraining' + self.ENABLE_INFERENCE = 'enableInference' + + # constants for determine whether create underlying azure resource + self.RELAY_SERVER_CONNECTION_STRING = 'relayServerConnectionString' # create relay connection string if None + self.SERVICE_BUS_CONNECTION_STRING = 'serviceBusConnectionString' # create service bus if None + self.LOG_ANALYTICS_WS_ENABLED = 'logAnalyticsWS' # create log analytics workspace if true + + # constants for azure resources creation + self.RELAY_HC_AUTH_NAME = 'azureml_rw' + self.SERVICE_BUS_COMPUTE_STATE_TOPIC = 'computestate-updatedby-computeprovider' + self.SERVICE_BUS_COMPUTE_STATE_SUB = 'compute-scheduler-computestate' + self.SERVICE_BUS_JOB_STATE_TOPIC = 'jobstate-updatedby-computeprovider' + self.SERVICE_BUS_JOB_STATE_SUB = 'compute-scheduler-jobstate' + + # reference mapping + self.reference_mapping = { + self.RELAY_SERVER_CONNECTION_STRING: [self.RELAY_CONNECTION_STRING_KEY, self.RELAY_CONNECTION_STRING_DEPRECATED_KEY], + self.SERVICE_BUS_CONNECTION_STRING: [self.SERVICE_BUS_CONNECTION_STRING_KEY], + 'cluster_name': ['clusterId', 'prometheus.prometheusSpec.externalLabels.cluster_name'], + } + + def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, + scope, auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file): + if scope == 'namespace': + raise InvalidArgumentValueError("Invalid scope '{}'. This extension can be installed " + "only at 'cluster' scope.".format(scope)) + if not release_namespace: + release_namespace = self.DEFAULT_RELEASE_NAMESPACE + scope_cluster = ScopeCluster(release_namespace=release_namespace) + ext_scope = Scope(cluster=scope_cluster, namespace=None) + + # validate the config + self.__validate_config(configuration_settings, configuration_protected_settings) + + # get the arc's location + subscription_id = get_subscription_id(cmd.cli_ctx) + cluster_rp, parent_api_version = _get_cluster_rp_api_version(cluster_type) + cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}' \ + '/{3}/{4}'.format(subscription_id, resource_group_name, cluster_rp, cluster_type, cluster_name) + cluster_location = '' + resources = cf_resources(cmd.cli_ctx, subscription_id) + try: + resource = resources.get_by_id( + cluster_resource_id, parent_api_version) + cluster_location = resource.location.lower() + except CloudError as ex: + raise ex + + # generate values for the extension if none is set. + configuration_settings['cluster_name'] = configuration_settings.get('cluster_name', cluster_resource_id) + configuration_settings['domain'] = configuration_settings.get( + 'doamin', '{}.cloudapp.azure.com'.format(cluster_location)) + configuration_settings['location'] = configuration_settings.get('location', cluster_location) + configuration_settings[self.JOB_SCHEDULER_LOCATION_KEY] = configuration_settings.get( + self.JOB_SCHEDULER_LOCATION_KEY, cluster_location) + configuration_settings[self.CLUSTER_NAME_FRIENDLY_KEY] = configuration_settings.get( + self.CLUSTER_NAME_FRIENDLY_KEY, cluster_name) + + # create Azure resources need by the extension based on the config. + self.__create_required_resource( + cmd, configuration_settings, configuration_protected_settings, subscription_id, resource_group_name, + cluster_name, cluster_location) + + # dereference + configuration_settings = _dereference(self.reference_mapping, configuration_settings) + configuration_protected_settings = _dereference(self.reference_mapping, configuration_protected_settings) + + # If release-train is not input, set it to 'stable' + if release_train is None: + release_train = 'stable' + + create_identity = True + extension_instance = Extension( + extension_type=extension_type, + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version, + scope=ext_scope, + configuration_settings=configuration_settings, + configuration_protected_settings=configuration_protected_settings, + identity=None, + location="" + ) + return extension_instance, name, create_identity + + + def __validate_config(self, configuration_settings, configuration_protected_settings): + # perform basic validation of the input config + config_keys = configuration_settings.keys() + config_protected_keys = configuration_protected_settings.keys() + dup_keys = set(config_keys) & set(config_protected_keys) + if len(dup_keys) > 0: + for key in dup_keys: + logger.warning( + 'Duplicate keys found in both configuration settings and configuration protected setttings: %s', key) + raise InvalidArgumentValueError("Duplicate keys found.") + + enable_training = _get_value_from_config_protected_config( + self.ENABLE_TRAINING, configuration_settings, configuration_protected_settings) + enable_training = str(enable_training).lower() == 'true' + + enable_inference = _get_value_from_config_protected_config( + self.ENABLE_INFERENCE, configuration_settings, configuration_protected_settings) + enable_inference = str(enable_inference).lower() == 'true' + + if enable_inference: + logger.warning("The installed AzureML extension for AML inference is experimental and not covered by customer support. Please use with discretion.") + elif not (enable_training or enable_inference): + raise InvalidArgumentValueError( + "Please create Microsoft.AzureML.Kubernetes extension instance either " + "for Machine Learning training or inference by specifying " + f"'--configuration-settings {self.ENABLE_TRAINING}=true' or '--configuration-settings {self.ENABLE_INFERENCE}=true'") + + self.__validate_scoring_fe_settings(configuration_settings, configuration_protected_settings) + + configuration_settings[self.ENABLE_TRAINING] = configuration_settings.get(self.ENABLE_TRAINING, enable_training) + configuration_settings[self.ENABLE_INFERENCE] = configuration_settings.get( + self.ENABLE_INFERENCE, enable_inference) + configuration_protected_settings.pop(self.ENABLE_TRAINING, None) + configuration_protected_settings.pop(self.ENABLE_INFERENCE, None) + + def __validate_scoring_fe_settings(self, configuration_settings, configuration_protected_settings): + clusterPurpose = _get_value_from_config_protected_config( + 'clusterPurpose', configuration_settings, configuration_protected_settings) + if clusterPurpose and clusterPurpose not in ["DevTest", "FastProd"]: + raise InvalidArgumentValueError( + "Accepted values for '--configuration-settings clusterPurpose' " + "are 'DevTest' and 'FastProd'") + + feSslCert = _get_value_from_config_protected_config( + 'scoringFe.sslCert', configuration_settings, configuration_protected_settings) + sslKey = _get_value_from_config_protected_config( + 'scoringFe.sslKey', configuration_settings, configuration_protected_settings) + allowInsecureConnections = _get_value_from_config_protected_config( + 'allowInsecureConnections', configuration_settings, configuration_protected_settings) + allowInsecureConnections = str(allowInsecureConnections).lower() == 'true' + if (not feSslCert or not sslKey) and not allowInsecureConnections: + raise InvalidArgumentValueError( + "Provide ssl certificate and key. " + "Otherwise explicitly allow insecure connection by specifying " + "'--configuration-settings allowInsecureConnections=true'") + + feIsInternalLoadBalancer = _get_value_from_config_protected_config( + 'scoringFe.serviceType.internalLoadBalancer', configuration_settings, configuration_protected_settings) + feIsInternalLoadBalancer = str(feIsInternalLoadBalancer).lower() == 'true' + if feIsInternalLoadBalancer: + logger.warning( + 'Internal load balancer only supported on AKS and AKS Engine Clusters.') + + def __create_required_resource( + self, cmd, configuration_settings, configuration_protected_settings, subscription_id, resource_group_name, + cluster_name, cluster_location): + if str(configuration_settings.get(self.LOG_ANALYTICS_WS_ENABLED, False)).lower() == 'true'\ + and not configuration_settings.get(self.AZURE_LOG_ANALYTICS_CONNECTION_STRING)\ + and not configuration_protected_settings.get(self.AZURE_LOG_ANALYTICS_CONNECTION_STRING): + logger.info('==== BEGIN LOG ANALYTICS WORKSPACE CREATION ====') + ws_costumer_id, shared_key = _get_log_analytics_ws_connection_string( + cmd, subscription_id, resource_group_name, cluster_name, cluster_location) + logger.info('==== END LOG ANALYTICS WORKSPACE CREATION ====') + configuration_settings[self.AZURE_LOG_ANALYTICS_ENABLED_KEY] = True + configuration_settings[self.AZURE_LOG_ANALYTICS_CUSTOMER_ID_KEY] = ws_costumer_id + configuration_protected_settings[self.AZURE_LOG_ANALYTICS_CONNECTION_STRING] = shared_key + + if not configuration_settings.get( + self.RELAY_SERVER_CONNECTION_STRING) and not configuration_protected_settings.get( + self.RELAY_SERVER_CONNECTION_STRING): + logger.info('==== BEGIN RELAY CREATION ====') + relay_connection_string, hc_resource_id, hc_name = _get_relay_connection_str( + cmd, subscription_id, resource_group_name, cluster_name, cluster_location, self.RELAY_HC_AUTH_NAME) + logger.info('==== END RELAY CREATION ====') + configuration_protected_settings[self.RELAY_SERVER_CONNECTION_STRING] = relay_connection_string + configuration_settings[self.HC_RESOURCE_ID_KEY] = hc_resource_id + configuration_settings[self.RELAY_HC_NAME_KEY] = hc_name + + if not configuration_settings.get( + self.SERVICE_BUS_CONNECTION_STRING) and not configuration_protected_settings.get( + self.SERVICE_BUS_CONNECTION_STRING): + logger.info('==== BEGIN SERVICE BUS CREATION ====') + topic_sub_mapping = { + self.SERVICE_BUS_COMPUTE_STATE_TOPIC: self.SERVICE_BUS_COMPUTE_STATE_SUB, + self.SERVICE_BUS_JOB_STATE_TOPIC: self.SERVICE_BUS_JOB_STATE_SUB + } + service_bus_connection_string, service_buse_resource_id = _get_service_bus_connection_string( + cmd, subscription_id, resource_group_name, cluster_name, cluster_location, topic_sub_mapping) + logger.info('==== END SERVICE BUS CREATION ====') + configuration_protected_settings[self.SERVICE_BUS_CONNECTION_STRING] = service_bus_connection_string + configuration_settings[self.SERVICE_BUS_RESOURCE_ID_KEY] = service_buse_resource_id + configuration_settings[f'{self.SERVICE_BUS_TOPIC_SUB_MAPPING_KEY}.{self.SERVICE_BUS_COMPUTE_STATE_TOPIC}'] = self.SERVICE_BUS_COMPUTE_STATE_SUB + configuration_settings[f'{self.SERVICE_BUS_TOPIC_SUB_MAPPING_KEY}.{self.SERVICE_BUS_JOB_STATE_TOPIC}'] = self.SERVICE_BUS_JOB_STATE_SUB + + +def _get_valid_name(input_name: str, suffix_len: int, max_len: int) -> str: + normalized_str = ''.join(filter(str.isalnum, input_name)) + assert len(normalized_str) > 0, "normalized name empty" + + if len(normalized_str) <= max_len: + return normalized_str + + if suffix_len > max_len: + logger.warning( + "suffix length is bigger than max length. Set suffix length to max length.") + suffix_len = max_len + + md5_suffix = md5(input_name.encode("utf8")).hexdigest()[:suffix_len] + new_name = normalized_str[:max_len - suffix_len] + md5_suffix + return new_name + + +def _lock_resource(cmd, lock_scope, lock_level='CanNotDelete'): + lock_client: azure.mgmt.resource.locks.ManagementLockClient = get_mgmt_service_client( + cmd.cli_ctx, azure.mgmt.resource.locks.ManagementLockClient) + # put lock on relay resource + lock_object = ManagementLockObject(level=lock_level, notes='locked by amlk8s.') + try: + lock_client.management_locks.create_or_update_by_scope( + scope=lock_scope, lock_name='amlk8s-resource-lock', parameters=lock_object) + except: + # try to lock the resource if user has the owner privilege + pass + + +def _get_relay_connection_str( + cmd, subscription_id, resource_group_name, cluster_name, cluster_location, auth_rule_name) -> Tuple[ + str, str, str]: + relay_client: azure.mgmt.relay.RelayManagementClient = get_mgmt_service_client( + cmd.cli_ctx, azure.mgmt.relay.RelayManagementClient) + + cluster_id = '{}-{}-{}-relay'.format(cluster_name, subscription_id, resource_group_name) + # create namespace + relay_namespace_name = _get_valid_name( + cluster_id, suffix_len=6, max_len=50) + relay_namespace_params = azure.mgmt.relay.models.RelayNamespace( + location=cluster_location, tags=resource_tag) + + async_poller = relay_client.namespaces.create_or_update( + resource_group_name, relay_namespace_name, relay_namespace_params) + while True: + async_poller.result(15) + if async_poller.done(): + break + + # create hybrid connection + hybrid_connection_name = cluster_name + hybrid_connection_object = relay_client.hybrid_connections.create_or_update( + resource_group_name, relay_namespace_name, hybrid_connection_name, requires_client_authorization=True) + + # relay_namespace_ojbect = relay_client.namespaces.get(resource_group_name, relay_namespace_name) + # relay_namespace_resource_id = relay_namespace_ojbect.id + # _lock_resource(cmd, lock_scope=relay_namespace_resource_id) + + # create authorization rule + auth_rule_rights = [azure.mgmt.relay.models.AccessRights.manage, + azure.mgmt.relay.models.AccessRights.send, azure.mgmt.relay.models.AccessRights.listen] + relay_client.hybrid_connections.create_or_update_authorization_rule( + resource_group_name, relay_namespace_name, hybrid_connection_name, auth_rule_name, rights=auth_rule_rights) + + # get connection string + key: azure.mgmt.relay.models.AccessKeys = relay_client.hybrid_connections.list_keys( + resource_group_name, relay_namespace_name, hybrid_connection_name, auth_rule_name) + return f'{key.primary_connection_string}', hybrid_connection_object.id, hybrid_connection_name + + +def _get_service_bus_connection_string(cmd, subscription_id, resource_group_name, cluster_name, cluster_location, + topic_sub_mapping: Dict[str, str]) -> Tuple[str, str]: + service_bus_client: azure.mgmt.servicebus.ServiceBusManagementClient = get_mgmt_service_client( + cmd.cli_ctx, azure.mgmt.servicebus.ServiceBusManagementClient) + cluster_id = '{}-{}-{}-service-bus'.format(cluster_name, + subscription_id, resource_group_name) + service_bus_namespace_name = _get_valid_name( + cluster_id, suffix_len=6, max_len=50) + + # create namespace + service_bus_sku = azure.mgmt.servicebus.models.SBSku( + name=azure.mgmt.servicebus.models.SkuName.standard.name) + service_bus_namespace = azure.mgmt.servicebus.models.SBNamespace( + location=cluster_location, + sku=service_bus_sku, + tags=resource_tag) + async_poller = service_bus_client.namespaces.create_or_update( + resource_group_name, service_bus_namespace_name, service_bus_namespace) + while True: + async_poller.result(15) + if async_poller.done(): + break + + for topic_name, service_bus_subscription_name in topic_sub_mapping.items(): + # create topic + topic = azure.mgmt.servicebus.models.SBTopic(max_size_in_megabytes=5120, default_message_time_to_live='P60D') + service_bus_client.topics.create_or_update( + resource_group_name, service_bus_namespace_name, topic_name, topic) + + # create subscription + sub = azure.mgmt.servicebus.models.SBSubscription( + max_delivery_count=1, default_message_time_to_live='P14D', lock_duration='PT30S') + service_bus_client.subscriptions.create_or_update( + resource_group_name, service_bus_namespace_name, topic_name, service_bus_subscription_name, sub) + + service_bus_object = service_bus_client.namespaces.get(resource_group_name, service_bus_namespace_name) + service_bus_resource_id = service_bus_object.id + # _lock_resource(cmd, service_bus_resource_id) + + # get connection string + auth_rules = service_bus_client.namespaces.list_authorization_rules( + resource_group_name, service_bus_namespace_name) + for rule in auth_rules: + key: azure.mgmt.servicebus.models.AccessKeys = service_bus_client.namespaces.list_keys( + resource_group_name, service_bus_namespace_name, rule.name) + return key.primary_connection_string, service_bus_resource_id + + +def _get_log_analytics_ws_connection_string( + cmd, subscription_id, resource_group_name, cluster_name, cluster_location) -> Tuple[ + str, str]: + log_analytics_ws_client: azure.mgmt.loganalytics.LogAnalyticsManagementClient = get_mgmt_service_client( + cmd.cli_ctx, azure.mgmt.loganalytics.LogAnalyticsManagementClient) + + # create workspace + cluster_id = '{}-{}-{}'.format(cluster_name, subscription_id, resource_group_name) + log_analytics_ws_name = _get_valid_name(cluster_id, suffix_len=6, max_len=63) + log_analytics_ws = azure.mgmt.loganalytics.models.Workspace(location=cluster_location, tags=resource_tag) + async_poller = log_analytics_ws_client.workspaces.begin_create_or_update( + resource_group_name, log_analytics_ws_name, log_analytics_ws) + customer_id = '' + # log_analytics_ws_resource_id = '' + while True: + log_analytics_ws_object = async_poller.result(15) + if async_poller.done(): + customer_id = log_analytics_ws_object.customer_id + # log_analytics_ws_resource_id = log_analytics_ws_object.id + break + + # _lock_resource(cmd, log_analytics_ws_resource_id) + + # get workspace shared keys + shared_key = log_analytics_ws_client.shared_keys.get_shared_keys( + resource_group_name, log_analytics_ws_name).primary_shared_key + return customer_id, shared_key + + +def _dereference(ref_mapping_dict: Dict[str, List], output_dict: Dict[str, Any]): + output_dict = copy.deepcopy(output_dict) + for ref_key, ref_list in ref_mapping_dict.items(): + if ref_key not in output_dict: + continue + ref_value = output_dict[ref_key] + for key in ref_list: + # if user has set the value, skip. + output_dict[key] = output_dict.get(key, ref_value) + return output_dict + + +def _get_value_from_config_protected_config(key, config, protected_config): + if key in config: + return config[key] + return protected_config.get(key) + + +def _get_cluster_rp_api_version(cluster_type) -> Tuple[str, str]: + rp = '' + parent_api_version = '' + if cluster_type.lower() == 'connectedclusters': + rp = 'Microsoft.Kubernetes' + parent_api_version = '2020-01-01-preview' + elif cluster_type.lower() == 'appliances': + rp = 'Microsoft.ResourceConnector' + parent_api_version = '2020-09-15-privatepreview' + elif cluster_type.lower() == '': + rp = 'Microsoft.ContainerService' + parent_api_version = '2017-07-01' + else: + raise InvalidArgumentValueError("Error! Cluster type '{}' is not supported".format(cluster_type)) + return rp, parent_api_version diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py b/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py new file mode 100644 index 00000000000..30f33c6b31a --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py @@ -0,0 +1,45 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument + +from ..vendored_sdks.models import Extension +from ..vendored_sdks.models import ScopeCluster +from ..vendored_sdks.models import ScopeNamespace +from ..vendored_sdks.models import Scope + +from .PartnerExtensionModel import PartnerExtensionModel + + +class Cassandra(PartnerExtensionModel): + def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, + scope, auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file): + + """Default validations & defaults for Create + Must create and return a valid 'Extension' object. + + """ + ext_scope = None + if scope is not None: + if scope.lower() == 'cluster': + scope_cluster = ScopeCluster(release_namespace=release_namespace) + ext_scope = Scope(cluster=scope_cluster, namespace=None) + elif scope.lower() == 'namespace': + scope_namespace = ScopeNamespace(target_namespace=target_namespace) + ext_scope = Scope(namespace=scope_namespace, cluster=None) + + create_identity = True + extension_instance = Extension( + extension_type=extension_type, + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version, + scope=ext_scope, + configuration_settings=configuration_settings, + configuration_protected_settings=configuration_protected_settings, + ) + return extension_instance, name, create_identity diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py new file mode 100644 index 00000000000..e066b953fb3 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py @@ -0,0 +1,447 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument + +import datetime +import json + +from knack.log import get_logger + +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.core.commands import LongRunningOperation +from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id +from azure.cli.core.util import sdk_no_wait +from msrestazure.azure_exceptions import CloudError +from msrestazure.tools import parse_resource_id, is_valid_resource_id + +from ..vendored_sdks.models import Extension +from ..vendored_sdks.models import ScopeCluster +from ..vendored_sdks.models import Scope + +from .PartnerExtensionModel import PartnerExtensionModel + +from .._client_factory import ( + cf_resources, cf_resource_groups, cf_log_analytics) + +logger = get_logger(__name__) + + +class ContainerInsights(PartnerExtensionModel): + def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, + scope, auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file): + + """ExtensionType 'microsoft.azuremonitor.containers' specific validations & defaults for Create + Must create and return a valid 'ExtensionInstance' object. + + """ + # NOTE-1: Replace default scope creation with your customization! + ext_scope = None + # Hardcoding name, release_namespace and scope since container-insights only supports one instance and cluster + # scope and platform doesnt have support yet extension specific constraints like this + name = 'azuremonitor-containers' + release_namespace = 'azuremonitor-containers' + # Scope is always cluster + scope_cluster = ScopeCluster(release_namespace=release_namespace) + ext_scope = Scope(cluster=scope_cluster, namespace=None) + + is_ci_extension_type = True + + logger.warning('Ignoring name, release-namespace and scope parameters since %s ' + 'only supports cluster scope and single instance of this extension.', extension_type) + logger.warning("Defaulting to extension name '%s' and release-namespace '%s'", name, release_namespace) + + _get_container_insights_settings(cmd, resource_group_name, cluster_name, configuration_settings, + configuration_protected_settings, is_ci_extension_type) + + # NOTE-2: Return a valid ExtensionInstance object, Instance name and flag for Identity + create_identity = True + extension_instance = Extension( + extension_type=extension_type, + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version, + scope=ext_scope, + configuration_settings=configuration_settings, + configuration_protected_settings=configuration_protected_settings + ) + return extension_instance, name, create_identity + + +# Custom Validation Logic for Container Insights + +def _invoke_deployment(cmd, resource_group_name, deployment_name, template, parameters, validate, no_wait, + subscription_id=None): + from azure.cli.core.profiles import ResourceType + deployment_properties = cmd.get_models('DeploymentProperties', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) + properties = deployment_properties(template=template, parameters=parameters, mode='incremental') + smc = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, + subscription_id=subscription_id).deployments + if validate: + logger.info('==== BEGIN TEMPLATE ====') + logger.info(json.dumps(template, indent=2)) + logger.info('==== END TEMPLATE ====') + + if cmd.supported_api_version(min_api='2019-10-01', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES): + deployment_temp = cmd.get_models('Deployment', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) + deployment = deployment_temp(properties=properties) + + if validate: + validation_poller = smc.validate(resource_group_name, deployment_name, deployment) + return LongRunningOperation(cmd.cli_ctx)(validation_poller) + return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, deployment) + + if validate: + return smc.validate(resource_group_name, deployment_name, properties) + return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, properties) + + +def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, + cluster_resource_group_name, cluster_name): + # mapping for azure public cloud + # log analytics workspaces cannot be created in WCUS region due to capacity limits + # so mapped to EUS per discussion with log analytics team + # pylint: disable=too-many-locals,too-many-statements + + azurecloud_location_to_oms_region_code_map = { + "australiasoutheast": "ASE", + "australiaeast": "EAU", + "australiacentral": "CAU", + "canadacentral": "CCA", + "centralindia": "CIN", + "centralus": "CUS", + "eastasia": "EA", + "eastus": "EUS", + "eastus2": "EUS2", + "eastus2euap": "EAP", + "francecentral": "PAR", + "japaneast": "EJP", + "koreacentral": "SE", + "northeurope": "NEU", + "southcentralus": "SCUS", + "southeastasia": "SEA", + "uksouth": "SUK", + "usgovvirginia": "USGV", + "westcentralus": "EUS", + "westeurope": "WEU", + "westus": "WUS", + "westus2": "WUS2" + } + azurecloud_region_to_oms_region_map = { + "australiacentral": "australiacentral", + "australiacentral2": "australiacentral", + "australiaeast": "australiaeast", + "australiasoutheast": "australiasoutheast", + "brazilsouth": "southcentralus", + "canadacentral": "canadacentral", + "canadaeast": "canadacentral", + "centralus": "centralus", + "centralindia": "centralindia", + "eastasia": "eastasia", + "eastus": "eastus", + "eastus2": "eastus2", + "francecentral": "francecentral", + "francesouth": "francecentral", + "japaneast": "japaneast", + "japanwest": "japaneast", + "koreacentral": "koreacentral", + "koreasouth": "koreacentral", + "northcentralus": "eastus", + "northeurope": "northeurope", + "southafricanorth": "westeurope", + "southafricawest": "westeurope", + "southcentralus": "southcentralus", + "southeastasia": "southeastasia", + "southindia": "centralindia", + "uksouth": "uksouth", + "ukwest": "uksouth", + "westcentralus": "eastus", + "westeurope": "westeurope", + "westindia": "centralindia", + "westus": "westus", + "westus2": "westus2" + } + + # mapping for azure china cloud + # currently log analytics supported only China East 2 region + azurechina_location_to_oms_region_code_map = { + "chinaeast": "EAST2", + "chinaeast2": "EAST2", + "chinanorth": "EAST2", + "chinanorth2": "EAST2" + } + azurechina_region_to_oms_region_map = { + "chinaeast": "chinaeast2", + "chinaeast2": "chinaeast2", + "chinanorth": "chinaeast2", + "chinanorth2": "chinaeast2" + } + + # mapping for azure us governmner cloud + azurefairfax_location_to_oms_region_code_map = { + "usgovvirginia": "USGV" + } + azurefairfax_region_to_oms_region_map = { + "usgovvirginia": "usgovvirginia" + } + + cluster_location = '' + resources = cf_resources(cmd.cli_ctx, subscription_id) + + cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Kubernetes' \ + '/connectedClusters/{2}'.format(subscription_id, cluster_resource_group_name, cluster_name) + try: + resource = resources.get_by_id(cluster_resource_id, '2020-01-01-preview') + cluster_location = resource.location.lower() + except CloudError as ex: + raise ex + + cloud_name = cmd.cli_ctx.cloud.name.lower() + workspace_region = "eastus" + workspace_region_code = "EUS" + + # sanity check that locations and clouds match. + if ((cloud_name == 'azurecloud' and azurechina_region_to_oms_region_map.get(cluster_location, False)) or + (cloud_name == 'azurecloud' and azurefairfax_region_to_oms_region_map.get(cluster_location, False))): + raise InvalidArgumentValueError( + 'Wrong cloud (azurecloud) setting for region {}, please use "az cloud set ..."' + .format(cluster_location) + ) + + if ((cloud_name == 'azurechinacloud' and azurecloud_region_to_oms_region_map.get(cluster_location, False)) or + (cloud_name == 'azurechinacloud' and azurefairfax_region_to_oms_region_map.get(cluster_location, False))): + raise InvalidArgumentValueError( + 'Wrong cloud (azurechinacloud) setting for region {}, please use "az cloud set ..."' + .format(cluster_location) + ) + + if ((cloud_name == 'azureusgovernment' and azurecloud_region_to_oms_region_map.get(cluster_location, False)) or + (cloud_name == 'azureusgovernment' and azurechina_region_to_oms_region_map.get(cluster_location, False))): + raise InvalidArgumentValueError( + 'Wrong cloud (azureusgovernment) setting for region {}, please use "az cloud set ..."' + .format(cluster_location) + ) + + if cloud_name == 'azurecloud': + workspace_region = azurecloud_region_to_oms_region_map.get(cluster_location, "eastus") + workspace_region_code = azurecloud_location_to_oms_region_code_map.get(workspace_region, "EUS") + elif cloud_name == 'azurechinacloud': + workspace_region = azurechina_region_to_oms_region_map.get(cluster_location, "chinaeast2") + workspace_region_code = azurechina_location_to_oms_region_code_map.get(workspace_region, "EAST2") + elif cloud_name == 'azureusgovernment': + workspace_region = azurefairfax_region_to_oms_region_map.get(cluster_location, "usgovvirginia") + workspace_region_code = azurefairfax_location_to_oms_region_code_map.get(workspace_region, "USGV") + else: + logger.error("AKS Monitoring addon not supported in cloud : %s", cloud_name) + + default_workspace_resource_group = 'DefaultResourceGroup-' + workspace_region_code + default_workspace_name = 'DefaultWorkspace-{0}-{1}'.format(subscription_id, workspace_region_code) + default_workspace_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OperationalInsights' \ + '/workspaces/{2}'.format(subscription_id, default_workspace_resource_group, default_workspace_name) + resource_groups = cf_resource_groups(cmd.cli_ctx, subscription_id) + + # check if default RG exists + if resource_groups.check_existence(default_workspace_resource_group): + try: + resource = resources.get_by_id(default_workspace_resource_id, '2015-11-01-preview') + return resource.id + except CloudError as ex: + if ex.status_code != 404: + raise ex + else: + resource_groups.create_or_update(default_workspace_resource_group, { + 'location': workspace_region}) + + default_workspace_params = { + 'location': workspace_region, + 'properties': { + 'sku': { + 'name': 'standalone' + } + } + } + async_poller = resources.create_or_update_by_id(default_workspace_resource_id, '2015-11-01-preview', + default_workspace_params) + + ws_resource_id = '' + while True: + result = async_poller.result(15) + if async_poller.done(): + ws_resource_id = result.id + break + + return ws_resource_id + + +def _ensure_container_insights_for_monitoring(cmd, workspace_resource_id): + # extract subscription ID and resource group from workspace_resource_id URL + parsed = parse_resource_id(workspace_resource_id) + subscription_id, resource_group = parsed["subscription"], parsed["resource_group"] + + resources = cf_resources(cmd.cli_ctx, subscription_id) + try: + resource = resources.get_by_id(workspace_resource_id, '2015-11-01-preview') + location = resource.location + except CloudError as ex: + raise ex + + unix_time_in_millis = int( + (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000.0) + + solution_deployment_name = 'ContainerInsights-{}'.format(unix_time_in_millis) + + # pylint: disable=line-too-long + template = { + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "workspaceResourceId": { + "type": "string", + "metadata": { + "description": "Azure Monitor Log Analytics Resource ID" + } + }, + "workspaceRegion": { + "type": "string", + "metadata": { + "description": "Azure Monitor Log Analytics workspace region" + } + }, + "solutionDeploymentName": { + "type": "string", + "metadata": { + "description": "Name of the solution deployment" + } + } + }, + "resources": [ + { + "type": "Microsoft.Resources/deployments", + "name": "[parameters('solutionDeploymentName')]", + "apiVersion": "2017-05-10", + "subscriptionId": "[split(parameters('workspaceResourceId'),'/')[2]]", + "resourceGroup": "[split(parameters('workspaceResourceId'),'/')[4]]", + "properties": { + "mode": "Incremental", + "template": { + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": {}, + "variables": {}, + "resources": [ + { + "apiVersion": "2015-11-01-preview", + "type": "Microsoft.OperationsManagement/solutions", + "location": "[parameters('workspaceRegion')]", + "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')" + "[8], ')')]", + "properties": { + "workspaceResourceId": "[parameters('workspaceResourceId')]" + }, + "plan": { + "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId')," + "'/')[8], ')')]", + "product": "[Concat('OMSGallery/', 'ContainerInsights')]", + "promotionCode": "", + "publisher": "Microsoft" + } + } + ] + }, + "parameters": {} + } + } + ] + } + + params = { + "workspaceResourceId": { + "value": workspace_resource_id + }, + "workspaceRegion": { + "value": location + }, + "solutionDeploymentName": { + "value": solution_deployment_name + } + } + + deployment_name = 'arc-k8s-monitoring-{}'.format(unix_time_in_millis) + # publish the Container Insights solution to the Log Analytics workspace + return _invoke_deployment(cmd, resource_group, deployment_name, template, params, + validate=False, no_wait=False, subscription_id=subscription_id) + + +def _get_container_insights_settings(cmd, cluster_resource_group_name, cluster_name, configuration_settings, + configuration_protected_settings, is_ci_extension_type): + + subscription_id = get_subscription_id(cmd.cli_ctx) + workspace_resource_id = '' + + if configuration_settings is not None: + if 'loganalyticsworkspaceresourceid' in configuration_settings: + configuration_settings['logAnalyticsWorkspaceResourceID'] = \ + configuration_settings.pop('loganalyticsworkspaceresourceid') + + if 'logAnalyticsWorkspaceResourceID' in configuration_settings: + workspace_resource_id = configuration_settings['logAnalyticsWorkspaceResourceID'] + + workspace_resource_id = workspace_resource_id.strip() + + if configuration_protected_settings is not None: + if 'proxyEndpoint' in configuration_protected_settings: + # current supported format for proxy endpoint is http(s)://:@: + # do some basic validation since the ci agent does the complete validation + proxy = configuration_protected_settings['proxyEndpoint'].strip().lower() + proxy_parts = proxy.split('://') + if (not proxy) or (not proxy.startswith('http://') and not proxy.startswith('https://')) or \ + (len(proxy_parts) != 2): + raise InvalidArgumentValueError( + 'proxyEndpoint url should in this format http(s)://:@:' + ) + logger.info("successfully validated proxyEndpoint url hence passing proxy endpoint to extension") + configuration_protected_settings['omsagent.proxy'] = configuration_protected_settings['proxyEndpoint'] + + if not workspace_resource_id: + workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring( + cmd, subscription_id, cluster_resource_group_name, cluster_name) + else: + if not is_valid_resource_id(workspace_resource_id): + raise InvalidArgumentValueError('{} is not a valid Azure resource ID.'.format(workspace_resource_id)) + + if is_ci_extension_type: + _ensure_container_insights_for_monitoring(cmd, workspace_resource_id).result() + + # extract subscription ID and resource group from workspace_resource_id URL + parsed = parse_resource_id(workspace_resource_id) + workspace_sub_id, workspace_rg_name, workspace_name = \ + parsed["subscription"], parsed["resource_group"], parsed["name"] + + log_analytics_client = cf_log_analytics(cmd.cli_ctx, workspace_sub_id) + log_analytics_workspace = log_analytics_client.workspaces.get(workspace_rg_name, workspace_name) + if not log_analytics_workspace: + raise InvalidArgumentValueError( + 'Fails to retrieve workspace by {}'.format(workspace_name)) + + shared_keys = log_analytics_client.shared_keys.get_shared_keys( + workspace_rg_name, workspace_name) + if not shared_keys: + raise InvalidArgumentValueError('Fails to retrieve shared key for workspace {}'.format( + log_analytics_workspace)) + configuration_protected_settings['omsagent.secret.wsid'] = log_analytics_workspace.customer_id + configuration_settings['logAnalyticsWorkspaceResourceID'] = workspace_resource_id + configuration_protected_settings['omsagent.secret.key'] = shared_keys.primary_shared_key + # set the domain for the ci agent for non azure public clouds + cloud_name = cmd.cli_ctx.cloud.name + if cloud_name.lower() == 'azurechinacloud': + configuration_settings['omsagent.domain'] = 'opinsights.azure.cn' + elif cloud_name.lower() == 'azureusgovernment': + configuration_settings['omsagent.domain'] = 'opinsights.azure.us' + elif cloud_name.lower() == 'usnat': + configuration_settings['omsagent.domain'] = 'opinsights.azure.eaglex.ic.gov' + elif cloud_name.lower() == 'ussec': + configuration_settings['omsagent.domain'] = 'opinsights.azure.microsoft.scloud' diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py new file mode 100644 index 00000000000..73b57215d7f --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py @@ -0,0 +1,46 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument + +from ..vendored_sdks.models import Extension +from ..vendored_sdks.models import ScopeCluster +from ..vendored_sdks.models import ScopeNamespace +from ..vendored_sdks.models import Scope + +from .PartnerExtensionModel import PartnerExtensionModel + + +class DefaultExtension(PartnerExtensionModel): + def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, + scope, auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file): + + """Default validations & defaults for Create + Must create and return a valid 'ExtensionInstance' object. + + """ + ext_scope = None + if scope is not None: + if scope.lower() == 'cluster': + scope_cluster = ScopeCluster(release_namespace=release_namespace) + ext_scope = Scope(cluster=scope_cluster, namespace=None) + elif scope.lower() == 'namespace': + scope_namespace = ScopeNamespace(target_namespace=target_namespace) + ext_scope = Scope(namespace=scope_namespace, cluster=None) + + create_identity = False + extension_instance = Extension( + extension_type=extension_type, + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version, + scope=ext_scope, + configuration_settings=configuration_settings, + configuration_protected_settings=configuration_protected_settings + ) + return extension_instance, name, create_identity + diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py b/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py new file mode 100644 index 00000000000..0b7c00efaa6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py @@ -0,0 +1,22 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from abc import ABC, abstractmethod +from ..vendored_sdks.models import Extension + + +class PartnerExtensionModel(ABC): + @abstractmethod + def Create(self, cmd, client, resource_group_name: str, cluster_name: str, name: str, cluster_type: str, + extension_type: str, scope: str, auto_upgrade_minor_version: bool, release_train: str, version: str, + target_namespace: str, release_namespace: str, configuration_settings: dict, + configuration_protected_settings: dict, configuration_settings_file: str, + configuration_protected_settings_file: str) -> Extension: + pass + + # @abstractmethod + # def Update(self, extension: ExtensionInstance, auto_upgrade_minor_version: bool, + # release_train: str, version: str) -> ExtensionInstanceUpdate: + # pass diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py b/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py new file mode 100644 index 00000000000..99c0f28cd71 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py @@ -0,0 +1,5 @@ +# ----------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ----------------------------------------------------------------------------- diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py new file mode 100644 index 00000000000..c8473283ca2 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -0,0 +1,176 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument,too-many-locals + +from knack.log import get_logger + +from msrestazure.azure_exceptions import CloudError + +from azure.cli.core.azclierror import ResourceNotFoundError, MutuallyExclusiveArgumentError, \ + InvalidArgumentValueError, CommandNotFoundError, RequiredArgumentMissingError +from azure.cli.core.commands.client_factory import get_subscription_id +from ..vendored_sdks.models import Identity +from ..vendored_sdks.models import Scope + +from ..partner_extensions.ContainerInsights import ContainerInsights +from ..partner_extensions.AzureDefender import AzureDefender +from ..partner_extensions.Cassandra import Cassandra +from ..partner_extensions.AzureMLKubernetes import AzureMLKubernetes +from ..partner_extensions.DefaultExtension import DefaultExtension +from ..utils import get_cluster_rp, read_config_settings_file + +from .._client_factory import cf_resources + +logger = get_logger(__name__) + + +# A factory method to return the correct extension class based off of the extension name +def ExtensionFactory(extension_name): + extension_map = { + 'microsoft.azuremonitor.containers': ContainerInsights, + 'microsoft.azuredefender.kubernetes': AzureDefender, + 'microsoft.azureml.kubernetes': AzureMLKubernetes, + 'cassandradatacentersoperator': Cassandra, + } + + # Return the extension if we find it in the map, else return the default + return extension_map.get(extension_name, DefaultExtension)() + + +class ExtensionProvider: + def __init__(self, cmd, client, resource_group_name, cluster_name, cluster_type, name=None): + self.cmd = cmd + self.client = client + self.resource_group_name = resource_group_name + self.cluster_name = cluster_name + self.cluster_type = cluster_type + self.name = name + self.cluster_rp = get_cluster_rp(cluster_type) + + + def create(self, extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, + version=None, target_namespace=None, release_namespace=None, configuration_settings=None, + configuration_protected_settings=None, configuration_settings_file=None, + configuration_protected_settings_file=None, tags=None): + """Create a new Extension Instance. + + """ + extension_type_lower = extension_type.lower() + + # Configuration Settings & Configuration Protected Settings + if configuration_settings is not None and configuration_settings_file is not None: + raise MutuallyExclusiveArgumentError( + 'Error! Both configuration-settings and configuration-settings-file cannot be provided.' + ) + + if configuration_protected_settings is not None and configuration_protected_settings_file is not None: + raise MutuallyExclusiveArgumentError( + 'Error! Both configuration-protected-settings and configuration-protected-settings-file ' + 'cannot be provided.' + ) + + config_settings = {} + config_protected_settings = {} + # Get Configuration Settings from file + if configuration_settings_file is not None: + config_settings = read_config_settings_file(configuration_settings_file) + + if configuration_settings is not None: + for dicts in configuration_settings: + for key, value in dicts.items(): + config_settings[key] = value + + # Get Configuration Protected Settings from file + if configuration_protected_settings_file is not None: + config_protected_settings = read_config_settings_file(configuration_protected_settings_file) + + if configuration_protected_settings is not None: + for dicts in configuration_protected_settings: + for key, value in dicts.items(): + config_protected_settings[key] = value + + # Identity is not created by default. Extension type must specify if identity is required. + create_identity = False + extension_instance = None + + # Scope & Namespace validation - common to all extension-types + self.__validate_scope_and_namespace(scope, release_namespace, target_namespace) + + # Give Partners a chance to their extensionType specific validations and to set value over-rides. + + # Get the extension class based on the extension name + extension_class = ExtensionFactory(extension_type_lower) + extension_instance, name, create_identity = extension_class.Create( + self.cmd, self.client, self.resource_group_name, self.cluster_name, self.name, self.cluster_type, extension_type_lower, scope, + auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, config_settings, + config_protected_settings, configuration_settings_file, configuration_protected_settings_file) + + # Common validations + self.__validate_version_and_auto_upgrade(extension_instance.version, extension_instance.auto_upgrade_minor_version) + self.__validate_scope_after_customization(extension_instance.scope) + + # Create identity, if required + if create_identity: + extension_instance.identity, extension_instance.location = self.__create_identity() + + # Try to create the resource + return self.client.create(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name, name, extension_instance) + + def __validate_scope_and_namespace(scope, release_namespace, target_namespace): + if scope == 'cluster': + if target_namespace is not None: + message = "When --scope is 'cluster', --target-namespace must not be given." + raise MutuallyExclusiveArgumentError(message) + else: + if release_namespace is not None: + message = "When --scope is 'namespace', --release-namespace must not be given." + raise MutuallyExclusiveArgumentError(message) + + + def __validate_scope_after_customization(self, scope_obj): + if scope_obj is not None and scope_obj.namespace is not None and scope_obj.namespace.target_namespace is None: + message = "When --scope is 'namespace', --target-namespace must be given." + raise RequiredArgumentMissingError(message) + + + def __validate_version_and_auto_upgrade(self, version, auto_upgrade_minor_version): + if version is not None: + if auto_upgrade_minor_version: + message = "To pin to specific version, auto-upgrade-minor-version must be set to 'false'." + raise MutuallyExclusiveArgumentError(message) + + auto_upgrade_minor_version = False + + + def __create_identity(self): + subscription_id = get_subscription_id(self.cmd.cli_ctx) + resources = cf_resources(self.cmd.cli_ctx, subscription_id) + + cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}'.format(subscription_id, + self.resource_group_name, + self.cluster_rp, + self.cluster_type, + self.cluster_name) + + if self.cluster_rp == 'Microsoft.Kubernetes': + parent_api_version = '2020-01-01-preview' + elif self.cluster_rp == 'Microsoft.ResourceConnector': + parent_api_version = '2020-09-15-privatepreview' + elif self.cluster_rp == 'Microsoft.ContainerService': + parent_api_version = '2017-07-01' + else: + raise InvalidArgumentValueError( + "Error! Cluster type '{}' is not supported for extension identity".format(self.cluster_type) + ) + + try: + resource = resources.get_by_id(cluster_resource_id, parent_api_version) + location = str(resource.location.lower()) + except CloudError as ex: + raise ex + identity_type = "SystemAssigned" + + return Identity(type=identity_type), location \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py new file mode 100644 index 00000000000..522d0745e66 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -0,0 +1,163 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError +from azure.core.exceptions import HttpResponseError +from .._client_factory import ( + k8s_config_sourcecontrol_client, + k8s_config_extension_client +) +from ..utils import get_cluster_rp, get_data_from_key_or_file, get_protected_settings +from ..validators import ( + validate_cc_registration, + validate_known_hosts, + validate_repository_ref, + validate_duration, + validate_git_repository, + validate_kustomization_list, + validate_private_key, + validate_url_with_params +) +from .. import consts +from ..vendored_sdks.models import ( + FluxConfiguration, + GitRepositoryDefinition, + RepositoryRefDefinition, +) +from .ExtensionProvider import ExtensionProvider + + +class FluxConfigurationProvider: + def __init__(self, cmd, client, resource_group_name, cluster_name, cluster_type, name=None): + self.extension_provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type) + self.cmd = cmd + self.client = client + self.resource_group_name = resource_group_name + self.cluster_name = cluster_name + self.cluster_type = cluster_type + self.name = name + self.cluster_rp = get_cluster_rp(cluster_type) + + + def show(self): + """Get an existing Kubernetes Source Control Configuration. + + """ + # Determine ClusterRP + try: + config = self.client.get(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + return config + except HttpResponseError as ex: + # Customize the error message for resources not found + if ex.response.status_code == 404: + # If Cluster not found + if ex.message.__contains__("(ResourceNotFound)"): + message = ex.message + recommendation = 'Verify that the --cluster-type is correct and the Resource ' \ + '{0}/{1}/{2} exists'.format(self.cluster_rp, self.cluster_type, self.cluster_name) + # If Configuration not found + elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): + message = '(ConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \ + 'fluxConfigurations/{3} could not be found!'.format(self.cluster_rp, self.cluster_type, + self.cluster_name, self.name) + recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \ + '/fluxConfigurations/{3} exists'.format(self.cluster_rp, self.cluster_type, + self.cluster_name, self.name) + else: + message = ex.message + recommendation = '' + raise ResourceNotFoundError(message, recommendation) from ex + + + # pylint: disable=too-many-locals + def create(self, url=None, scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, + branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, + ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + known_hosts_file=None, kustomization=None): + + # Pre-Validation + validate_repository_ref(branch, tag, semver, commit) + validate_duration("--timeout", timeout) + validate_duration("--sync-interval", sync_interval) + + if kustomization: + validate_kustomization_list(kustomization) + + # Validate if we are able to install the flux configuration + scc_client = k8s_config_sourcecontrol_client(self.cmd.cli_ctx) + configs = scc_client.list(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name) + # configs is an iterable, no len() so we have to iterate to check for configs + for _ in configs: + raise DeploymentError( + consts.SCC_EXISTS_ON_CLUSTER_ERROR, + consts.SCC_EXISTS_ON_CLUSTER_HELP) + + # Validate if the extension is installed, if not, install it + extension_client = k8s_config_extension_client(self.cmd.cli_ctx) + extensions = extension_client.list(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name) + found_flux_extension = False + for extension in extensions: + if extension.extension_type.lower() == consts.FLUX_EXTENSION_TYPE: + found_flux_extension = True + break + if not found_flux_extension: + self.extension_provider.create(self.cmd, self.client, self.resource_group_name, self.cluster_name, self.name, self.cluster_type, + consts.FLUX_EXTENSION_TYPE, "cluster") + + # Get the protected settings and validate the private key value + protected_settings = get_protected_settings( + ssh_private_key, ssh_private_key_file, https_user, https_key + ) + if consts.SSH_PRIVATE_KEY_KEY in protected_settings: + validate_private_key(protected_settings['sshPrivateKey']) + + # Get the known hosts data and validate it + knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file) + if knownhost_data: + validate_known_hosts(knownhost_data) + + # Validate registration with the RP endpoint + validate_cc_registration(self.cmd) + + git_repository = GitRepositoryDefinition() + dp_source_kind = consts.GIT_REPOSITORY + + if kind == consts.GIT: + validate_git_repository(url) + validate_url_with_params(url, ssh_private_key, ssh_private_key_file, + known_hosts, known_hosts_file, https_user, https_key) + repository_ref = RepositoryRefDefinition( + branch=branch, + tag=tag, + semver=semver, + commit=commit + ) + git_repository = GitRepositoryDefinition( + url=url, + timeout=timeout, + sync_interval=sync_interval, + repository_ref=repository_ref, + ssh_known_hosts=knownhost_data, + https_user=https_user, + auth_ref_override=auth_ref_override + ) + + flux_configuration = FluxConfiguration( + scope=scope, + namespace=namespace, + source_kind=dp_source_kind, + timeout=timeout, + sync_interval=sync_interval, + git_repository=git_repository, + kustomizations=kustomization + ) + + return self.client.begin_create_or_update(self.resource_group_name, self.cluster_rp, + self.cluster_type, self.cluster_name, self.name, flux_configuration) + + + def delete(self, client, resource_group_name, cluster_name, cluster_type, name): + cluster_rp = get_cluster_rp(cluster_type) + return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/__init__.py b/src/k8s-config/azext_k8s_config/providers/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index cdb4eb2233b..5e9db364106 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -4,6 +4,7 @@ # -------------------------------------------------------------------------------------------- import base64 +import json from azure.cli.core.azclierror import ( MutuallyExclusiveArgumentError, InvalidArgumentValueError, @@ -12,7 +13,7 @@ from . import consts -def get_cluster_type(cluster_type): +def get_cluster_rp(cluster_type): if cluster_type.lower() == consts.CONNECTED_CLUSTERS: return consts.CONNECTED_RP_NAMESPACE # Since cluster_type is an enum of only two values, if not connectedClusters, it will be managedClusters. @@ -57,6 +58,20 @@ def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, ht return protected_settings +def read_config_settings_file(file_path): + try: + config_file = open(file_path,) + settings = json.load(config_file) + except ValueError: + raise Exception("File {} is not a valid JSON file".format(file_path)) + + files = len(settings) + if files == 0: + raise Exception("File {} is empty".format(file_path)) + + return settings + + def read_key_file(path): try: with open(path, "r") as myfile: # user passed in filename From 08ac8993e694a54f4210c7b0d724dc0714f3cbe3 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 4 Jun 2021 12:09:46 -0700 Subject: [PATCH 08/61] Updated the versioned sdks --- src/k8s-config/azext_k8s_config/custom.py | 2 +- .../vendored_sdks/_configuration.py | 1 - .../_source_control_configuration_client.py | 20 +-- .../vendored_sdks/aio/_configuration.py | 1 - .../_source_control_configuration_client.py | 20 +-- .../vendored_sdks/aio/operations/__init__.py | 8 +- .../_cluster_extension_type_operations.py | 6 +- .../_cluster_extension_types_operations.py | 2 +- .../_extension_type_versions_operations.py | 2 +- .../aio/operations/_extensions_operations.py | 8 +- .../_flux_configurations_operations.py | 8 +- .../_location_extension_types_operations.py | 2 +- .../_operation_status_operations.py | 154 ++++++++--------- ...ource_control_configurations_operations.py | 8 +- .../vendored_sdks/models/__init__.py | 4 +- ...urce_control_configuration_client_enums.py | 4 +- .../vendored_sdks/operations/__init__.py | 8 +- .../_cluster_extension_type_operations.py | 6 +- .../_cluster_extension_types_operations.py | 2 +- .../_extension_type_versions_operations.py | 2 +- .../operations/_extensions_operations.py | 8 +- .../_flux_configurations_operations.py | 8 +- .../_location_extension_types_operations.py | 2 +- .../_operation_status_operations.py | 156 +++++++++--------- ...ource_control_configurations_operations.py | 8 +- 25 files changed, 224 insertions(+), 226 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index c4228fc0e07..52bb58d3050 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -22,7 +22,7 @@ def flux_config_create(cmd, client, resource_group_name, cluster_name, name, clu ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): - provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, name, cluster_type) + provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) return provider.create(url, scope, namespace, kind, timeout, sync_interval, branch, tag, semver, commit, auth_ref_override, ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py index 27f67e28de4..5888f4f24f9 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py @@ -48,7 +48,6 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-06-01-preview" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) self._configure(**kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py index e0be530cfde..87eac4ae470 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py @@ -19,8 +19,6 @@ from azure.core.pipeline.transport import HttpRequest, HttpResponse from ._configuration import SourceControlConfigurationClientConfiguration -from .operations import FluxConfigurationsOperations -from .operations import FluxConfigOperationStatusOperations from .operations import ExtensionsOperations from .operations import OperationStatusOperations from .operations import ClusterExtensionTypeOperations @@ -28,6 +26,8 @@ from .operations import ExtensionTypeVersionsOperations from .operations import LocationExtensionTypesOperations from .operations import SourceControlConfigurationsOperations +from .operations import FluxConfigurationsOperations +from .operations import FluxConfigOperationStatusOperations from .operations import Operations from . import models @@ -35,10 +35,6 @@ class SourceControlConfigurationClient(object): """KubernetesConfiguration Client. - :ivar flux_configurations: FluxConfigurationsOperations operations - :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.operations.FluxConfigurationsOperations - :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations - :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.operations.FluxConfigOperationStatusOperations :ivar extensions: ExtensionsOperations operations :vartype extensions: azure.mgmt.kubernetesconfiguration.operations.ExtensionsOperations :ivar operation_status: OperationStatusOperations operations @@ -53,6 +49,10 @@ class SourceControlConfigurationClient(object): :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.operations.LocationExtensionTypesOperations :ivar source_control_configurations: SourceControlConfigurationsOperations operations :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.operations.SourceControlConfigurationsOperations + :ivar flux_configurations: FluxConfigurationsOperations operations + :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.operations.FluxConfigurationsOperations + :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations + :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.operations.FluxConfigOperationStatusOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.kubernetesconfiguration.operations.Operations :param credential: Credential needed for the client to connect to Azure. @@ -81,10 +81,6 @@ def __init__( self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - self.flux_configurations = FluxConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.flux_config_operation_status = FluxConfigOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize) self.extensions = ExtensionsOperations( self._client, self._config, self._serialize, self._deserialize) self.operation_status = OperationStatusOperations( @@ -99,6 +95,10 @@ def __init__( self._client, self._config, self._serialize, self._deserialize) self.source_control_configurations = SourceControlConfigurationsOperations( self._client, self._config, self._serialize, self._deserialize) + self.flux_configurations = FluxConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.flux_config_operation_status = FluxConfigOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py index 510c9921e82..a78247ced4d 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py @@ -45,7 +45,6 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2021-06-01-preview" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) self._configure(**kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py index a60b069516a..899010cc672 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py @@ -17,8 +17,6 @@ from azure.core.credentials_async import AsyncTokenCredential from ._configuration import SourceControlConfigurationClientConfiguration -from .operations import FluxConfigurationsOperations -from .operations import FluxConfigOperationStatusOperations from .operations import ExtensionsOperations from .operations import OperationStatusOperations from .operations import ClusterExtensionTypeOperations @@ -26,6 +24,8 @@ from .operations import ExtensionTypeVersionsOperations from .operations import LocationExtensionTypesOperations from .operations import SourceControlConfigurationsOperations +from .operations import FluxConfigurationsOperations +from .operations import FluxConfigOperationStatusOperations from .operations import Operations from .. import models @@ -33,10 +33,6 @@ class SourceControlConfigurationClient(object): """KubernetesConfiguration Client. - :ivar flux_configurations: FluxConfigurationsOperations operations - :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigurationsOperations - :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations - :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigOperationStatusOperations :ivar extensions: ExtensionsOperations operations :vartype extensions: azure.mgmt.kubernetesconfiguration.aio.operations.ExtensionsOperations :ivar operation_status: OperationStatusOperations operations @@ -51,6 +47,10 @@ class SourceControlConfigurationClient(object): :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.aio.operations.LocationExtensionTypesOperations :ivar source_control_configurations: SourceControlConfigurationsOperations operations :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.aio.operations.SourceControlConfigurationsOperations + :ivar flux_configurations: FluxConfigurationsOperations operations + :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigurationsOperations + :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations + :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigOperationStatusOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.kubernetesconfiguration.aio.operations.Operations :param credential: Credential needed for the client to connect to Azure. @@ -78,10 +78,6 @@ def __init__( self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - self.flux_configurations = FluxConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.flux_config_operation_status = FluxConfigOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize) self.extensions = ExtensionsOperations( self._client, self._config, self._serialize, self._deserialize) self.operation_status = OperationStatusOperations( @@ -96,6 +92,10 @@ def __init__( self._client, self._config, self._serialize, self._deserialize) self.source_control_configurations = SourceControlConfigurationsOperations( self._client, self._config, self._serialize, self._deserialize) + self.flux_configurations = FluxConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.flux_config_operation_status = FluxConfigOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py index 84aa36f0694..ee01fecd439 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py @@ -6,8 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._flux_configurations_operations import FluxConfigurationsOperations -from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations from ._extensions_operations import ExtensionsOperations from ._operation_status_operations import OperationStatusOperations from ._cluster_extension_type_operations import ClusterExtensionTypeOperations @@ -15,11 +13,11 @@ from ._extension_type_versions_operations import ExtensionTypeVersionsOperations from ._location_extension_types_operations import LocationExtensionTypesOperations from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._flux_configurations_operations import FluxConfigurationsOperations +from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations from ._operations import Operations __all__ = [ - 'FluxConfigurationsOperations', - 'FluxConfigOperationStatusOperations', 'ExtensionsOperations', 'OperationStatusOperations', 'ClusterExtensionTypeOperations', @@ -27,5 +25,7 @@ 'ExtensionTypeVersionsOperations', 'LocationExtensionTypesOperations', 'SourceControlConfigurationsOperations', + 'FluxConfigurationsOperations', + 'FluxConfigOperationStatusOperations', 'Operations', ] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py index f3a0857d94b..6f03630d6c4 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py @@ -44,7 +44,7 @@ async def get( self, resource_group_name: str, cluster_rp: Union[str, "_models.Enum0"], - cluster_type: Union[str, "_models.Enum9"], + cluster_type: Union[str, "_models.Enum5"], cluster_name: str, extension_type_name: str, **kwargs: Any @@ -58,7 +58,7 @@ async def get( :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 :param cluster_type: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum9 + :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum5 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_type_name: Extension type name. @@ -73,7 +73,7 @@ async def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py index 126adc7356b..72bc227a473 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py @@ -67,7 +67,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py index f89b757ee2a..f5e148e4704 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py @@ -63,7 +63,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py index a3de9bbcd00..16aa34e0fd6 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py @@ -58,7 +58,7 @@ async def _create_initial( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" @@ -228,7 +228,7 @@ async def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -283,7 +283,7 @@ async def _delete_initial( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -439,7 +439,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py index 1a33042d6b8..e6c7f967650 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py @@ -52,7 +52,7 @@ async def get( flux_configuration_name: str, **kwargs: Any ) -> "_models.FluxConfiguration": - """Gets details of the Source Control Configuration. + """Gets details of the Flux Configuration. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str @@ -186,7 +186,7 @@ async def begin_create_or_update( flux_configuration: "_models.FluxConfiguration", **kwargs: Any ) -> AsyncLROPoller["_models.FluxConfiguration"]: - """Create a new Kubernetes Source Control Configuration. + """Create a new Kubernetes Flux Configuration. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str @@ -328,8 +328,8 @@ async def begin_delete( force_delete: Optional[bool] = None, **kwargs: Any ) -> AsyncLROPoller[None]: - """This will delete the YAML file used to set up the Source control configuration, thus stopping - future sync from the source repo. + """This will delete the YAML file used to set up the Flux Configuration, thus stopping future sync + from the source repo. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py index ba8ecf56a96..f9a252028e5 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py @@ -60,7 +60,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py index 6cb43e77638..a8f41c82fe9 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py @@ -41,6 +41,83 @@ def __init__(self, client, config, serializer, deserializer) -> None: self._deserialize = deserializer self._config = config + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_name: str, + operation_id: str, + **kwargs: Any + ) -> "_models.OperationStatusResult": + """Get Async Operation status. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param operation_id: operation Id. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationStatusResult, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationStatusResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}/operations/{operationId}'} # type: ignore + def list( self, resource_group_name: str, @@ -125,80 +202,3 @@ async def get_next(next_link=None): get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore - - async def get( - self, - resource_group_name: str, - cluster_rp: Union[str, "_models.Enum0"], - cluster_resource_name: Union[str, "_models.Enum1"], - cluster_name: str, - extension_name: str, - operation_id: str, - **kwargs: Any - ) -> "_models.OperationStatusResult": - """Get Async Operation status. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - :type resource_group_name: str - :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS - clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 - :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters - (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 - :param cluster_name: The name of the kubernetes cluster. - :type cluster_name: str - :param extension_name: Name of the Extension. - :type extension_name: str - :param operation_id: operation Id. - :type operation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationStatusResult, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), - 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), - 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), - 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), - 'operationId': self._serialize.url("operation_id", operation_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('OperationStatusResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}/operations/{operationId}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py index 46e38a3d502..cc32dad8348 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py @@ -76,7 +76,7 @@ async def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -152,7 +152,7 @@ async def create_or_update( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" @@ -215,7 +215,7 @@ async def _delete_initial( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -364,7 +364,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py index 2d10e26a8b0..1c05522a343 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py @@ -81,7 +81,7 @@ CreatedByType, Enum0, Enum1, - Enum9, + Enum5, KustomizationValidationType, LevelType, MessageLevelType, @@ -133,7 +133,7 @@ 'CreatedByType', 'Enum0', 'Enum1', - 'Enum9', + 'Enum5', 'KustomizationValidationType', 'LevelType', 'MessageLevelType', diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py index 097c14df789..ab54da49fa4 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py @@ -62,7 +62,7 @@ class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): MANAGED_CLUSTERS = "managedClusters" CONNECTED_CLUSTERS = "connectedClusters" -class Enum9(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class Enum5(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): MANAGED_CLUSTERS = "managedClusters" CONNECTED_CLUSTERS = "connectedClusters" @@ -106,7 +106,7 @@ class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): FLUX = "Flux" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state of the resource. + """The provisioning state of the extension resource. """ SUCCEEDED = "Succeeded" diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py index 84aa36f0694..ee01fecd439 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py @@ -6,8 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._flux_configurations_operations import FluxConfigurationsOperations -from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations from ._extensions_operations import ExtensionsOperations from ._operation_status_operations import OperationStatusOperations from ._cluster_extension_type_operations import ClusterExtensionTypeOperations @@ -15,11 +13,11 @@ from ._extension_type_versions_operations import ExtensionTypeVersionsOperations from ._location_extension_types_operations import LocationExtensionTypesOperations from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._flux_configurations_operations import FluxConfigurationsOperations +from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations from ._operations import Operations __all__ = [ - 'FluxConfigurationsOperations', - 'FluxConfigOperationStatusOperations', 'ExtensionsOperations', 'OperationStatusOperations', 'ClusterExtensionTypeOperations', @@ -27,5 +25,7 @@ 'ExtensionTypeVersionsOperations', 'LocationExtensionTypesOperations', 'SourceControlConfigurationsOperations', + 'FluxConfigurationsOperations', + 'FluxConfigOperationStatusOperations', 'Operations', ] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py index f640b5aad94..fb463591017 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py @@ -48,7 +48,7 @@ def get( self, resource_group_name, # type: str cluster_rp, # type: Union[str, "_models.Enum0"] - cluster_type, # type: Union[str, "_models.Enum9"] + cluster_type, # type: Union[str, "_models.Enum5"] cluster_name, # type: str extension_type_name, # type: str **kwargs # type: Any @@ -63,7 +63,7 @@ def get( :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 :param cluster_type: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum9 + :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum5 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_type_name: Extension type name. @@ -78,7 +78,7 @@ def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py index 8655e283e4c..bc641f3595c 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py @@ -72,7 +72,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py index f536e0aa28d..8c8ca358711 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py @@ -68,7 +68,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py index 83323d2fc05..c0df1e38ae5 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py @@ -63,7 +63,7 @@ def _create_initial( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" @@ -235,7 +235,7 @@ def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -291,7 +291,7 @@ def _delete_initial( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -449,7 +449,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py index f2b55e3dd06..016272f00de 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py @@ -57,7 +57,7 @@ def get( **kwargs # type: Any ): # type: (...) -> "_models.FluxConfiguration" - """Gets details of the Source Control Configuration. + """Gets details of the Flux Configuration. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str @@ -193,7 +193,7 @@ def begin_create_or_update( **kwargs # type: Any ): # type: (...) -> LROPoller["_models.FluxConfiguration"] - """Create a new Kubernetes Source Control Configuration. + """Create a new Kubernetes Flux Configuration. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str @@ -337,8 +337,8 @@ def begin_delete( **kwargs # type: Any ): # type: (...) -> LROPoller[None] - """This will delete the YAML file used to set up the Source control configuration, thus stopping - future sync from the source repo. + """This will delete the YAML file used to set up the Flux Configuration, thus stopping future sync + from the source repo. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py index d273c577dc1..ff1ae940c42 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py @@ -65,7 +65,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py index 9bb4a643ab2..43efd5f16e8 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py @@ -45,6 +45,84 @@ def __init__(self, client, config, serializer, deserializer): self._deserialize = deserializer self._config = config + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_name, # type: str + operation_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.OperationStatusResult" + """Get Async Operation status. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_name: Name of the Extension. + :type extension_name: str + :param operation_id: operation Id. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: OperationStatusResult, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), + 'operationId': self._serialize.url("operation_id", operation_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('OperationStatusResult', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}/operations/{operationId}'} # type: ignore + def list( self, resource_group_name, # type: str @@ -130,81 +208,3 @@ def get_next(next_link=None): get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore - - def get( - self, - resource_group_name, # type: str - cluster_rp, # type: Union[str, "_models.Enum0"] - cluster_resource_name, # type: Union[str, "_models.Enum1"] - cluster_name, # type: str - extension_name, # type: str - operation_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.OperationStatusResult" - """Get Async Operation status. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - :type resource_group_name: str - :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS - clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 - :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters - (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 - :param cluster_name: The name of the kubernetes cluster. - :type cluster_name: str - :param extension_name: Name of the Extension. - :type extension_name: str - :param operation_id: operation Id. - :type operation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationStatusResult, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), - 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), - 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), - 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), - 'extensionName': self._serialize.url("extension_name", extension_name, 'str'), - 'operationId': self._serialize.url("operation_id", operation_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('OperationStatusResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionName}/operations/{operationId}'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py index 203755732f7..9d62e711f0e 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py @@ -81,7 +81,7 @@ def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -158,7 +158,7 @@ def create_or_update( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" @@ -222,7 +222,7 @@ def _delete_initial( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" # Construct URL @@ -373,7 +373,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): From 0c22363ec59af7230e6f02a5f8b4d1f1bf7fd5d0 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 9 Jun 2021 15:52:15 -0700 Subject: [PATCH 09/61] Push working command for testing --- src/k8s-config/azext_k8s_config/commands.py | 1 + src/k8s-config/azext_k8s_config/custom.py | 75 +++++++++++---------- 2 files changed, 41 insertions(+), 35 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 3049c30a8fd..c3c5d4c2ac8 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -19,3 +19,4 @@ def load_command_table(self, _): g.command('list', "list") g.custom_command('show', 'flux_config_show') g.custom_command('delete', 'flux_config_delete', confirmation=True) + g.custom_command('source create', 'flux_create_source', supports_local_cache=True) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 52bb58d3050..acbfcd4cec1 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -5,6 +5,12 @@ from .providers.ExtensionProvider import ExtensionProvider from .providers.FluxConfigurationProvider import FluxConfigurationProvider +from .vendored_sdks.models import ( + RepositoryRefDefinition, + GitRepositoryDefinition, + FluxConfiguration +) +from .utils import get_cluster_rp from . import consts def flux_config_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): @@ -34,42 +40,41 @@ def flux_config_delete(cmd, client, resource_group_name, cluster_name, cluster_t return provider.delete() -# def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, -# scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, -# auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, -# ssh_known_hosts=None, ssh_known_hosts_file=None): - -# # Determine ClusterRP -# cluster_rp = get_cluster_type(cluster_type) - -# repository_ref = RepositoryRefDefinition( -# branch=branch, -# tag=tag, -# semver=semver, -# commit=commit -# ) - -# git_repository = GitRepositoryDefinition( -# url=url, -# timeout=timeout, -# sync_interval=sync_interval, -# repository_ref=repository_ref, -# ssh_known_hosts=ssh_known_hosts, -# https_user=https_user, -# auth_ref_override=auth_ref_override -# ) +def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, + scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, + auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, + ssh_known_hosts=None, ssh_known_hosts_file=None): + from azure.cli.core.commands import cached_get, cached_put + + # Determine ClusterRP + cluster_rp = get_cluster_rp(cluster_type) + + repository_ref = RepositoryRefDefinition( + branch=branch, + tag=tag, + semver=semver, + commit=commit + ) + + git_repository = GitRepositoryDefinition( + url=url, + timeout=timeout, + sync_interval=sync_interval, + repository_ref=repository_ref, + ssh_known_hosts=ssh_known_hosts, + https_user=https_user, + auth_ref_override=auth_ref_override + ) -# flux_configuration = FluxConfiguration( -# scope=scope, -# namespace=namespace, -# source_kind=kind, -# timeout=timeout, -# sync_interval=sync_interval, -# git_repository=git_repository, -# kustomizations=[] -# ) -# # cache the payload if --defer used or send to Azure -# return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, name, cluster_rp, cluster_type, cluster_name) + flux_configuration = FluxConfiguration( + scope=scope, + namespace=namespace, + source_kind=kind, + git_repository=git_repository, + kustomizations=[] + ) + # cache the payload if --defer used or send to Azure + return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, cluster_rp, cluster_type, cluster_name, name) # def flux_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, # dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): From 90b30a889bcf7ac0813554bd25e2642061c046a3 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 11 Jun 2021 16:51:21 -0700 Subject: [PATCH 10/61] Update to multi api versioned sdk --- .../azext_k8s_config/_client_factory.py | 11 +- src/k8s-config/azext_k8s_config/_params.py | 49 +- src/k8s-config/azext_k8s_config/action.py | 34 +- src/k8s-config/azext_k8s_config/commands.py | 13 +- src/k8s-config/azext_k8s_config/consts.py | 6 + src/k8s-config/azext_k8s_config/custom.py | 19 +- .../partner_extensions/AzureDefender.py | 8 +- .../partner_extensions/AzureMLKubernetes.py | 7 +- .../partner_extensions/Cassandra.py | 10 +- .../partner_extensions/ContainerInsights.py | 12 +- .../partner_extensions/DefaultExtension.py | 10 +- .../PartnerExtensionModel.py | 2 +- .../partner_extensions/__init__.py | 2 + .../providers/ExtensionProvider.py | 6 +- .../providers/FluxConfigurationProvider.py | 2 +- .../vendored_sdks/__init__.py | 3 - .../vendored_sdks/_configuration.py | 13 +- .../_source_control_configuration_client.py | 320 +++++-- .../vendored_sdks/_version.py | 2 +- .../vendored_sdks/aio/_configuration.py | 15 +- .../_source_control_configuration_client.py | 325 +++++-- .../vendored_sdks/aio/operations/__init__.py | 16 - .../aio/operations/_operations.py | 7 +- ...ource_control_configurations_operations.py | 58 +- .../azext_k8s_config/vendored_sdks/models.py | 7 + .../v2020_07_01_preview/__init__.py | 19 + .../v2020_07_01_preview/_configuration.py | 71 ++ .../_source_control_configuration_client.py | 99 ++ .../v2020_07_01_preview/_version.py | 9 + .../v2020_07_01_preview/aio/__init__.py | 10 + .../v2020_07_01_preview/aio/_configuration.py | 67 ++ .../_source_control_configuration_client.py | 92 ++ .../aio/operations/__init__.py | 17 + .../aio/operations/_extensions_operations.py | 433 +++++++++ .../aio/operations/_operations.py | 105 +++ ...ource_control_configurations_operations.py | 420 +++++++++ .../v2020_07_01_preview/models/__init__.py | 99 ++ .../v2020_07_01_preview/models/_models.py | 817 ++++++++++++++++ .../v2020_07_01_preview/models/_models_py3.py | 890 ++++++++++++++++++ ...urce_control_configuration_client_enums.py | 102 ++ .../operations/__init__.py | 17 + .../operations/_extensions_operations.py | 442 +++++++++ .../operations/_operations.py | 110 +++ ...ource_control_configurations_operations.py | 429 +++++++++ .../v2020_10_01_preview/__init__.py | 19 + .../v2020_10_01_preview/_configuration.py | 71 ++ .../_source_control_configuration_client.py | 94 ++ .../v2020_10_01_preview/_version.py | 9 + .../v2020_10_01_preview/aio/__init__.py | 10 + .../v2020_10_01_preview/aio/_configuration.py | 67 ++ .../_source_control_configuration_client.py | 87 ++ .../aio/operations/__init__.py | 15 + .../aio/operations/_operations.py | 105 +++ ...ource_control_configurations_operations.py | 420 +++++++++ .../v2020_10_01_preview/models/__init__.py | 69 ++ .../v2020_10_01_preview/models/_models.py | 506 ++++++++++ .../v2020_10_01_preview/models/_models_py3.py | 549 +++++++++++ ...urce_control_configuration_client_enums.py | 78 ++ .../operations/__init__.py | 15 + .../operations/_operations.py | 110 +++ ...ource_control_configurations_operations.py | 429 +++++++++ .../vendored_sdks/v2021_03_01/__init__.py | 19 + .../v2021_03_01/_configuration.py | 71 ++ .../_source_control_configuration_client.py | 94 ++ .../vendored_sdks/v2021_03_01/_version.py | 9 + .../vendored_sdks/v2021_03_01/aio/__init__.py | 10 + .../v2021_03_01/aio/_configuration.py | 67 ++ .../_source_control_configuration_client.py | 87 ++ .../v2021_03_01/aio/operations/__init__.py | 15 + .../v2021_03_01/aio/operations/_operations.py | 105 +++ ...ource_control_configurations_operations.py | 420 +++++++++ .../v2021_03_01/models/__init__.py | 71 ++ .../v2021_03_01/models/_models.py | 495 ++++++++++ .../v2021_03_01/models/_models_py3.py | 540 +++++++++++ ...urce_control_configuration_client_enums.py | 87 ++ .../v2021_03_01/operations/__init__.py | 15 + .../v2021_03_01/operations/_operations.py | 110 +++ ...ource_control_configurations_operations.py | 429 +++++++++ .../v2021_05_01_preview/__init__.py | 19 + .../v2021_05_01_preview/_configuration.py | 71 ++ .../_source_control_configuration_client.py | 124 +++ .../v2021_05_01_preview/_version.py | 9 + .../v2021_05_01_preview/aio/__init__.py | 10 + .../v2021_05_01_preview/aio/_configuration.py | 67 ++ .../_source_control_configuration_client.py | 117 +++ .../aio}/operations/__init__.py | 4 - .../_cluster_extension_type_operations.py | 8 +- .../_cluster_extension_types_operations.py | 6 +- .../_extension_type_versions_operations.py | 4 +- .../aio/operations/_extensions_operations.py | 26 +- .../_location_extension_types_operations.py | 4 +- .../_operation_status_operations.py | 16 +- .../aio/operations/_operations.py | 105 +++ ...ource_control_configurations_operations.py | 420 +++++++++ .../models/__init__.py | 23 - .../models/_models.py | 374 +------- .../models/_models_py3.py | 405 +------- ...urce_control_configuration_client_enums.py | 30 - .../operations/__init__.py | 27 + .../_cluster_extension_type_operations.py | 8 +- .../_cluster_extension_types_operations.py | 6 +- .../_extension_type_versions_operations.py | 4 +- .../operations/_extensions_operations.py | 26 +- .../_location_extension_types_operations.py | 4 +- .../_operation_status_operations.py | 16 +- .../operations/_operations.py | 110 +++ ...ource_control_configurations_operations.py | 26 +- .../v2021_06_01_preview/__init__.py | 19 + .../v2021_06_01_preview/_configuration.py | 71 ++ .../_source_control_configuration_client.py | 104 ++ .../v2021_06_01_preview/_version.py | 9 + .../v2021_06_01_preview/aio/__init__.py | 10 + .../v2021_06_01_preview/aio/_configuration.py | 67 ++ .../_source_control_configuration_client.py | 97 ++ .../aio/operations/__init__.py | 19 + ...flux_config_operation_status_operations.py | 8 +- .../_flux_configurations_operations.py | 26 +- .../_operation_status_operations.py | 127 +++ .../aio/operations/_operations.py | 105 +++ .../v2021_06_01_preview/models/__init__.py | 80 ++ .../v2021_06_01_preview/models/_models.py | 692 ++++++++++++++ .../v2021_06_01_preview/models/_models_py3.py | 753 +++++++++++++++ ...urce_control_configuration_client_enums.py | 89 ++ .../operations/__init__.py | 19 + ...flux_config_operation_status_operations.py | 8 +- .../_flux_configurations_operations.py | 26 +- .../_operation_status_operations.py | 132 +++ .../operations/_operations.py | 4 +- 128 files changed, 13913 insertions(+), 1123 deletions(-) create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/models.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_version.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_version.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models_py3.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_version.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models_py3.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_version.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview/aio}/operations/__init__.py (84%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/aio/operations/_cluster_extension_type_operations.py (95%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/aio/operations/_cluster_extension_types_operations.py (96%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/aio/operations/_extension_type_versions_operations.py (97%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/aio/operations/_extensions_operations.py (97%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/aio/operations/_location_extension_types_operations.py (97%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/aio/operations/_operation_status_operations.py (95%) create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/models/__init__.py (84%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/models/_models.py (69%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/models/_models_py3.py (69%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/models/_source_control_configuration_client_enums.py (80%) create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/__init__.py rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/operations/_cluster_extension_type_operations.py (95%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/operations/_cluster_extension_types_operations.py (97%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/operations/_extension_type_versions_operations.py (97%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/operations/_extensions_operations.py (97%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/operations/_location_extension_types_operations.py (97%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/operations/_operation_status_operations.py (95%) create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operations.py rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_05_01_preview}/operations/_source_control_configurations_operations.py (96%) create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_version.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_configuration.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_06_01_preview}/aio/operations/_flux_config_operation_status_operations.py (95%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_06_01_preview}/aio/operations/_flux_configurations_operations.py (97%) create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/__init__.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models_py3.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/__init__.py rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_06_01_preview}/operations/_flux_config_operation_status_operations.py (95%) rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_06_01_preview}/operations/_flux_configurations_operations.py (97%) create mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py rename src/k8s-config/azext_k8s_config/vendored_sdks/{ => v2021_06_01_preview}/operations/_operations.py (96%) diff --git a/src/k8s-config/azext_k8s_config/_client_factory.py b/src/k8s-config/azext_k8s_config/_client_factory.py index f051ed7841b..a67cd99b59a 100644 --- a/src/k8s-config/azext_k8s_config/_client_factory.py +++ b/src/k8s-config/azext_k8s_config/_client_factory.py @@ -5,23 +5,24 @@ from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType +from . import consts -def k8s_config_client(cli_ctx, *_): +def k8s_config_client(cli_ctx, **kwargs): from azext_k8s_config.vendored_sdks import SourceControlConfigurationClient - return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient) + return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient, **kwargs) def k8s_config_fluxconfig_client(cli_ctx, *_): - return k8s_config_client(cli_ctx).flux_configurations + return k8s_config_client(cli_ctx, api_version=consts.FLUXCONFIG_API_VERSION).flux_configurations def k8s_config_sourcecontrol_client(cli_ctx, *_): - return k8s_config_client(cli_ctx).source_control_configurations + return k8s_config_client(cli_ctx, api_version=consts.SOURCE_CONTROL_API_VERSION).source_control_configurations def k8s_config_extension_client(cli_ctx, *_): - return k8s_config_client(cli_ctx).extensions + return k8s_config_client(cli_ctx, api_version=consts.EXTENSION_API_VERSION).extensions def resource_providers_client(cli_ctx): diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index d8f3f8637f3..7bffc25fdcd 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -8,10 +8,15 @@ from azure.cli.core.commands.validators import get_default_location_from_resource_group from azure.cli.core.commands.parameters import ( get_enum_type, + get_three_state_flag, tags_type ) from .validators import validate_configuration_name, validate_namespace -from .action import KustomizationAddAction +from .action import ( + KustomizationAddAction, + AddConfigurationProtectedSettings, + AddConfigurationSettings +) from . import consts @@ -90,6 +95,48 @@ def load_arguments(self, _): action=KustomizationAddAction, help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", nargs='+') + + with self.argument_context('k8s-config extension create') as c: + c.argument('scope', + arg_type=get_enum_type(['cluster', 'namespace']), + help='Specify the extension scope.') + c.argument('auto_upgrade_minor_version', + arg_group="Version", + options_list=['--auto-upgrade-minor-version', '--auto-upgrade'], + arg_type=get_three_state_flag(), + help='Automatically upgrade minor version of the extension instance.') + c.argument('version', + arg_group="Version", + help='Specify the version to install for the extension instance if' + ' --auto-upgrade-minor-version is not enabled.') + c.argument('release_train', + arg_group="Version", + help='Specify the release train for the extension type.') + c.argument('configuration_settings', + arg_group="Configuration", + options_list=['--configuration-settings', '--config'], + action=AddConfigurationSettings, + nargs='+', + help='Configuration Settings as key=value pair. Repeat parameter for each setting') + c.argument('configuration_protected_settings', + arg_group="Configuration", + options_list=['--configuration-protected-settings', '--config-protected'], + action=AddConfigurationProtectedSettings, + nargs='+', + help='Configuration Protected Settings as key=value pair. Repeat parameter for each setting') + c.argument('configuration_settings_file', + arg_group="Configuration", + options_list=['--configuration-settings-file', '--config-file'], + help='JSON file path for configuration-settings') + c.argument('configuration_protected_settings_file', + arg_group="Configuration", + options_list=['--configuration-protected-settings-file', '--config-protected-file'], + help='JSON file path for configuration-protected-settings') + c.argument('release_namespace', + help='Specify the namespace to install the extension release.') + c.argument('target_namespace', + help='Specify the target namespace to install to for the extension instance. This' + ' parameter is required if extension scope is set to \'namespace\'') # with self.argument_context('k8s-config flux source') as c: # c.argument('scope', diff --git a/src/k8s-config/azext_k8s_config/action.py b/src/k8s-config/azext_k8s_config/action.py index 105ec48f3dd..99c4bc6d6a7 100644 --- a/src/k8s-config/azext_k8s_config/action.py +++ b/src/k8s-config/azext_k8s_config/action.py @@ -5,8 +5,8 @@ # pylint: disable=protected-access import argparse -from azure.cli.core.azclierror import InvalidArgumentValueError -from .vendored_sdks.models import KustomizationDefinition +from azure.cli.core.azclierror import InvalidArgumentValueError, ArgumentUsageError +from .vendored_sdks.v2021_06_01_preview.models import KustomizationDefinition from .validators import validate_kustomization from . import consts from .utils import parse_dependencies @@ -35,3 +35,33 @@ def __call__(self, parser, namespace, values, option_string=None): KustomizationDefinition(depends_on=dependencies, sync_interval=sync_interval, **kwargs), option_string ) + + +# pylint: disable=protected-access, too-few-public-methods +class AddConfigurationSettings(argparse._AppendAction): + + def __call__(self, parser, namespace, values, option_string=None): + settings = {} + for item in values: + try: + key, value = item.split('=', 1) + settings[key] = value + except ValueError: + raise ArgumentUsageError('Usage error: {} configuration_setting_key=configuration_setting_value'. + format(option_string)) + super(AddConfigurationSettings, self).__call__(parser, namespace, settings, option_string) + + +# pylint: disable=protected-access, too-few-public-methods +class AddConfigurationProtectedSettings(argparse._AppendAction): + + def __call__(self, parser, namespace, values, option_string=None): + prot_settings = {} + for item in values: + try: + key, value = item.split('=', 1) + prot_settings[key] = value + except ValueError: + raise ArgumentUsageError('Usage error: {} configuration_protected_setting_key=' + 'configuration_protected_setting_value'.format(option_string)) + super(AddConfigurationProtectedSettings, self).__call__(parser, namespace, prot_settings, option_string) \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index c3c5d4c2ac8..d66ee32e851 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -5,7 +5,10 @@ # pylint: disable=line-too-long from azure.cli.core.commands import CliCommandType -from azext_k8s_config._client_factory import k8s_config_fluxconfig_client +from azext_k8s_config._client_factory import ( + k8s_config_fluxconfig_client, + k8s_config_extension_client +) def load_command_table(self, _): @@ -14,9 +17,17 @@ def load_command_table(self, _): client_factory=k8s_config_fluxconfig_client ) + k8s_config_extension_sdk = CliCommandType( + operations_tmpl='azext_k8s_config.vendored_sdks.operations#ExtensionsOperations.{}', + client_factory=k8s_config_extension_client + ) + with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_preview=True) as g: g.custom_command('create', 'flux_config_create') g.command('list', "list") g.custom_command('show', 'flux_config_show') g.custom_command('delete', 'flux_config_delete', confirmation=True) g.custom_command('source create', 'flux_create_source', supports_local_cache=True) + + with self.command_group('k8s-config extension', k8s_config_extension_client, client_factory=k8s_config_extension_client, is_preview=True) as g: + g.custom_command('create', 'extension_create') diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index ab570b0bcfd..e288ff12cd4 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -5,6 +5,12 @@ # pylint: disable=line-too-long +# API VERSIONS ----------------------------------------- + +EXTENSION_API_VERSION = '2020-07-01-preview' +SOURCE_CONTROL_API_VERSION = '2021-03-01' +FLUXCONFIG_API_VERSION = '2021-06-01-preview' + # ERROR/HELP TEXT DEFINITIONS ----------------------------------------- KUSTOMIZATION_REQUIRED_VALUES_MISSING_ERROR = "Error! Kustomization definition is invalid, required values {} not found" diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index acbfcd4cec1..74f98069a46 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -5,13 +5,14 @@ from .providers.ExtensionProvider import ExtensionProvider from .providers.FluxConfigurationProvider import FluxConfigurationProvider -from .vendored_sdks.models import ( +from .utils import get_cluster_rp +from . import consts + +from .vendored_sdks.v2021_06_01_preview.models import ( RepositoryRefDefinition, GitRepositoryDefinition, FluxConfiguration ) -from .utils import get_cluster_rp -from . import consts def flux_config_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): """Get an existing Kubernetes Source Control Configuration. @@ -40,6 +41,16 @@ def flux_config_delete(cmd, client, resource_group_name, cluster_name, cluster_t return provider.delete() +def extension_create(cmd, client, resource_group_name, cluster_name, name, cluster_type, + extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, + version=None, target_namespace=None, release_namespace=None, configuration_settings=None, + configuration_protected_settings=None, configuration_settings_file=None, + configuration_protected_settings_file=None, tags=None): + provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) + return provider.create(extension_type, scope, auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, + configuration_settings, configuration_protected_settings, configuration_settings_file, configuration_protected_settings_file) + + def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, @@ -47,7 +58,7 @@ def flux_create_source(cmd, client, resource_group_name, cluster_name, name, clu from azure.cli.core.commands import cached_get, cached_put # Determine ClusterRP - cluster_rp = get_cluster_rp(cluster_type) + cluster_rp = get_cluster_rp(cluster_type) repository_ref = RepositoryRefDefinition( branch=branch, diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py b/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py index 1496b7aad94..e5d70cdbabd 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py @@ -7,9 +7,11 @@ from knack.log import get_logger -from ..vendored_sdks.models import Extension -from ..vendored_sdks.models import ScopeCluster -from ..vendored_sdks.models import Scope +from ..vendored_sdks.v2021_05_01_preview.models import ( + Extension, + ScopeCluster, + Scope +) from .PartnerExtensionModel import PartnerExtensionModel from .ContainerInsights import _get_container_insights_settings diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py index 627e7feed3b..f42d62473b3 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py @@ -17,8 +17,11 @@ import azure.mgmt.storage.models import azure.mgmt.loganalytics import azure.mgmt.loganalytics.models -from ..vendored_sdks.models import ( - Extension, Scope, ScopeCluster) +from ..vendored_sdks.v2021_05_01_preview.models import( + Extension, + ScopeCluster, + Scope +) from azure.cli.core.azclierror import InvalidArgumentValueError from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id from azure.mgmt.resource.locks.models import ManagementLockObject diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py b/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py index 30f33c6b31a..e977cd2e77c 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py @@ -5,10 +5,12 @@ # pylint: disable=unused-argument -from ..vendored_sdks.models import Extension -from ..vendored_sdks.models import ScopeCluster -from ..vendored_sdks.models import ScopeNamespace -from ..vendored_sdks.models import Scope +from ..vendored_sdks.v2021_05_01_preview.models import( + Extension, + ScopeCluster, + ScopeNamespace, + Scope +) from .PartnerExtensionModel import PartnerExtensionModel diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py index e066b953fb3..e84abd12801 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py @@ -17,9 +17,11 @@ from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id, is_valid_resource_id -from ..vendored_sdks.models import Extension -from ..vendored_sdks.models import ScopeCluster -from ..vendored_sdks.models import Scope +from ..vendored_sdks.v2021_05_01_preview.models import( + Extension, + ScopeCluster, + Scope +) from .PartnerExtensionModel import PartnerExtensionModel @@ -93,11 +95,11 @@ def _invoke_deployment(cmd, resource_group_name, deployment_name, template, para if validate: validation_poller = smc.validate(resource_group_name, deployment_name, deployment) return LongRunningOperation(cmd.cli_ctx)(validation_poller) - return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, deployment) + return sdk_no_wait(no_wait, smc.begin_create_or_update, resource_group_name, deployment_name, deployment) if validate: return smc.validate(resource_group_name, deployment_name, properties) - return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, properties) + return sdk_no_wait(no_wait, smc.begin_create_or_update, resource_group_name, deployment_name, properties) def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py index 73b57215d7f..07b2c9c5ae3 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py @@ -5,10 +5,12 @@ # pylint: disable=unused-argument -from ..vendored_sdks.models import Extension -from ..vendored_sdks.models import ScopeCluster -from ..vendored_sdks.models import ScopeNamespace -from ..vendored_sdks.models import Scope +from ..vendored_sdks.v2021_05_01_preview.models import( + Extension, + ScopeCluster, + ScopeNamespace, + Scope +) from .PartnerExtensionModel import PartnerExtensionModel diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py b/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py index 0b7c00efaa6..a4ffa554e14 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py @@ -4,7 +4,7 @@ # -------------------------------------------------------------------------------------------- from abc import ABC, abstractmethod -from ..vendored_sdks.models import Extension +from ..vendored_sdks.v2021_05_01_preview.models import Extension class PartnerExtensionModel(ABC): diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py b/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py index 99c0f28cd71..7405deadd6b 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py @@ -3,3 +3,5 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # ----------------------------------------------------------------------------- + +from ..vendored_sdks.v2021_05_01_preview import models as models \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index c8473283ca2..d521f4de23f 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -12,8 +12,8 @@ from azure.cli.core.azclierror import ResourceNotFoundError, MutuallyExclusiveArgumentError, \ InvalidArgumentValueError, CommandNotFoundError, RequiredArgumentMissingError from azure.cli.core.commands.client_factory import get_subscription_id -from ..vendored_sdks.models import Identity -from ..vendored_sdks.models import Scope + +from ..vendored_sdks.v2021_05_01_preview.models import Identity from ..partner_extensions.ContainerInsights import ContainerInsights from ..partner_extensions.AzureDefender import AzureDefender @@ -119,7 +119,7 @@ def create(self, extension_type, scope=None, auto_upgrade_minor_version=None, re # Try to create the resource return self.client.create(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name, name, extension_instance) - def __validate_scope_and_namespace(scope, release_namespace, target_namespace): + def __validate_scope_and_namespace(self, scope, release_namespace, target_namespace): if scope == 'cluster': if target_namespace is not None: message = "When --scope is 'cluster', --target-namespace must not be given." diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 522d0745e66..a46a46c78d4 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -21,7 +21,7 @@ validate_url_with_params ) from .. import consts -from ..vendored_sdks.models import ( +from ..vendored_sdks.v2021_06_01_preview.models import ( FluxConfiguration, GitRepositoryDefinition, RepositoryRefDefinition, diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py index f13062376d7..b0a136e072d 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py @@ -7,9 +7,6 @@ # -------------------------------------------------------------------------- from ._source_control_configuration_client import SourceControlConfigurationClient -from ._version import VERSION - -__version__ = VERSION __all__ = ['SourceControlConfigurationClient'] try: diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py index 5888f4f24f9..d6b853c02a3 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py @@ -1,11 +1,13 @@ # 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. +# 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. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. # -------------------------------------------------------------------------- - from typing import TYPE_CHECKING from azure.core.configuration import Configuration @@ -20,7 +22,6 @@ from azure.core.credentials import TokenCredential - class SourceControlConfigurationClientConfiguration(Configuration): """Configuration for SourceControlConfigurationClient. @@ -29,7 +30,7 @@ class SourceControlConfigurationClientConfiguration(Configuration): :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str """ @@ -49,7 +50,7 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-kubernetesconfiguration/{}'.format(VERSION)) self._configure(**kwargs) def _configure( diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py index 87eac4ae470..825bb82bbfe 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py @@ -1,16 +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. +# 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. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin from msrest import Deserializer, Serializer +from ._configuration import SourceControlConfigurationClientConfiguration + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional @@ -18,117 +25,256 @@ from azure.core.credentials import TokenCredential from azure.core.pipeline.transport import HttpRequest, HttpResponse -from ._configuration import SourceControlConfigurationClientConfiguration -from .operations import ExtensionsOperations -from .operations import OperationStatusOperations -from .operations import ClusterExtensionTypeOperations -from .operations import ClusterExtensionTypesOperations -from .operations import ExtensionTypeVersionsOperations -from .operations import LocationExtensionTypesOperations -from .operations import SourceControlConfigurationsOperations -from .operations import FluxConfigurationsOperations -from .operations import FluxConfigOperationStatusOperations -from .operations import Operations -from . import models - - -class SourceControlConfigurationClient(object): +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class SourceControlConfigurationClient(MultiApiClientMixin, _SDKClient): """KubernetesConfiguration Client. - :ivar extensions: ExtensionsOperations operations - :vartype extensions: azure.mgmt.kubernetesconfiguration.operations.ExtensionsOperations - :ivar operation_status: OperationStatusOperations operations - :vartype operation_status: azure.mgmt.kubernetesconfiguration.operations.OperationStatusOperations - :ivar cluster_extension_type: ClusterExtensionTypeOperations operations - :vartype cluster_extension_type: azure.mgmt.kubernetesconfiguration.operations.ClusterExtensionTypeOperations - :ivar cluster_extension_types: ClusterExtensionTypesOperations operations - :vartype cluster_extension_types: azure.mgmt.kubernetesconfiguration.operations.ClusterExtensionTypesOperations - :ivar extension_type_versions: ExtensionTypeVersionsOperations operations - :vartype extension_type_versions: azure.mgmt.kubernetesconfiguration.operations.ExtensionTypeVersionsOperations - :ivar location_extension_types: LocationExtensionTypesOperations operations - :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.operations.LocationExtensionTypesOperations - :ivar source_control_configurations: SourceControlConfigurationsOperations operations - :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.operations.SourceControlConfigurationsOperations - :ivar flux_configurations: FluxConfigurationsOperations operations - :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.operations.FluxConfigurationsOperations - :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations - :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.operations.FluxConfigOperationStatusOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.kubernetesconfiguration.operations.Operations + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str - :param str base_url: Service URL + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ + DEFAULT_API_VERSION = '2021-03-01' + _PROFILE_TAG = "azure.mgmt.kubernetesconfiguration.SourceControlConfigurationClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + def __init__( self, credential, # type: "TokenCredential" subscription_id, # type: str + api_version=None, # type: Optional[str] base_url=None, # type: Optional[str] + profile=KnownProfiles.default, # type: KnownProfiles **kwargs # type: Any ): - # type: (...) -> None if not base_url: base_url = 'https://management.azure.com' self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(SourceControlConfigurationClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2020-07-01-preview: :mod:`v2020_07_01_preview.models` + * 2020-10-01-preview: :mod:`v2020_10_01_preview.models` + * 2021-03-01: :mod:`v2021_03_01.models` + * 2021-05-01-preview: :mod:`v2021_05_01_preview.models` + * 2021-06-01-preview: :mod:`v2021_06_01_preview.models` + """ + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview import models + return models + elif api_version == '2020-10-01-preview': + from .v2020_10_01_preview import models + return models + elif api_version == '2021-03-01': + from .v2021_03_01 import models + return models + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview import models + return models + elif api_version == '2021-06-01-preview': + from .v2021_06_01_preview import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def cluster_extension_type(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ClusterExtensionTypeOperations` + """ + api_version = self._get_api_version('cluster_extension_type') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ClusterExtensionTypeOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'cluster_extension_type'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def cluster_extension_types(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ClusterExtensionTypesOperations` + """ + api_version = self._get_api_version('cluster_extension_types') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ClusterExtensionTypesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'cluster_extension_types'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def extension_type_versions(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ExtensionTypeVersionsOperations` + """ + api_version = self._get_api_version('extension_type_versions') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ExtensionTypeVersionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'extension_type_versions'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def extensions(self): + """Instance depends on the API version: - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False - self._deserialize = Deserializer(client_models) - - self.extensions = ExtensionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operation_status = OperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize) - self.cluster_extension_type = ClusterExtensionTypeOperations( - self._client, self._config, self._serialize, self._deserialize) - self.cluster_extension_types = ClusterExtensionTypesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.extension_type_versions = ExtensionTypeVersionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.location_extension_types = LocationExtensionTypesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.source_control_configurations = SourceControlConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.flux_configurations = FluxConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.flux_config_operation_status = FluxConfigOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse - """Runs the network request through the client's chained policies. - - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + * 2020-07-01-preview: :class:`ExtensionsOperations` + * 2021-05-01-preview: :class:`ExtensionsOperations` """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + api_version = self._get_api_version('extensions') + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview.operations import ExtensionsOperations as OperationClass + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ExtensionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'extensions'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def flux_config_operation_status(self): + """Instance depends on the API version: + + * 2021-06-01-preview: :class:`FluxConfigOperationStatusOperations` + """ + api_version = self._get_api_version('flux_config_operation_status') + if api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import FluxConfigOperationStatusOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'flux_config_operation_status'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def flux_configurations(self): + """Instance depends on the API version: + + * 2021-06-01-preview: :class:`FluxConfigurationsOperations` + """ + api_version = self._get_api_version('flux_configurations') + if api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import FluxConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'flux_configurations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def location_extension_types(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`LocationExtensionTypesOperations` + """ + api_version = self._get_api_version('location_extension_types') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import LocationExtensionTypesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'location_extension_types'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def operation_status(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`OperationStatusOperations` + * 2021-06-01-preview: :class:`OperationStatusOperations` + """ + api_version = self._get_api_version('operation_status') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import OperationStatusOperations as OperationClass + elif api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import OperationStatusOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'operation_status'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def operations(self): + """Instance depends on the API version: + + * 2020-07-01-preview: :class:`Operations` + * 2020-10-01-preview: :class:`Operations` + * 2021-03-01: :class:`Operations` + * 2021-05-01-preview: :class:`Operations` + * 2021-06-01-preview: :class:`Operations` + """ + api_version = self._get_api_version('operations') + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview.operations import Operations as OperationClass + elif api_version == '2020-10-01-preview': + from .v2020_10_01_preview.operations import Operations as OperationClass + elif api_version == '2021-03-01': + from .v2021_03_01.operations import Operations as OperationClass + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import Operations as OperationClass + elif api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import Operations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def source_control_configurations(self): + """Instance depends on the API version: + + * 2020-07-01-preview: :class:`SourceControlConfigurationsOperations` + * 2020-10-01-preview: :class:`SourceControlConfigurationsOperations` + * 2021-03-01: :class:`SourceControlConfigurationsOperations` + * 2021-05-01-preview: :class:`SourceControlConfigurationsOperations` + """ + api_version = self._get_api_version('source_control_configurations') + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2020-10-01-preview': + from .v2020_10_01_preview.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2021-03-01': + from .v2021_03_01.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import SourceControlConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'source_control_configurations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) def close(self): - # type: () -> None self._client.close() - def __enter__(self): - # type: () -> SourceControlConfigurationClient self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_version.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_version.py index e5754a47ce6..b538e1b4f03 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/_version.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b1" +VERSION = "1.0.0b1" \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py index a78247ced4d..b715bf7d7e8 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py @@ -1,11 +1,13 @@ # 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. +# 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. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. # -------------------------------------------------------------------------- - from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -18,7 +20,6 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential - class SourceControlConfigurationClientConfiguration(Configuration): """Configuration for SourceControlConfigurationClient. @@ -27,7 +28,7 @@ class SourceControlConfigurationClientConfiguration(Configuration): :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str """ @@ -35,7 +36,7 @@ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - **kwargs: Any + **kwargs # type: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -46,7 +47,7 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-kubernetesconfiguration/{}'.format(VERSION)) self._configure(**kwargs) def _configure( diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py index 899010cc672..c32a60cfa69 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py @@ -1,127 +1,278 @@ # 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. +# 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. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. # -------------------------------------------------------------------------- from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin from msrest import Deserializer, Serializer +from ._configuration import SourceControlConfigurationClientConfiguration + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import SourceControlConfigurationClientConfiguration -from .operations import ExtensionsOperations -from .operations import OperationStatusOperations -from .operations import ClusterExtensionTypeOperations -from .operations import ClusterExtensionTypesOperations -from .operations import ExtensionTypeVersionsOperations -from .operations import LocationExtensionTypesOperations -from .operations import SourceControlConfigurationsOperations -from .operations import FluxConfigurationsOperations -from .operations import FluxConfigOperationStatusOperations -from .operations import Operations -from .. import models - - -class SourceControlConfigurationClient(object): +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class SourceControlConfigurationClient(MultiApiClientMixin, _SDKClient): """KubernetesConfiguration Client. - :ivar extensions: ExtensionsOperations operations - :vartype extensions: azure.mgmt.kubernetesconfiguration.aio.operations.ExtensionsOperations - :ivar operation_status: OperationStatusOperations operations - :vartype operation_status: azure.mgmt.kubernetesconfiguration.aio.operations.OperationStatusOperations - :ivar cluster_extension_type: ClusterExtensionTypeOperations operations - :vartype cluster_extension_type: azure.mgmt.kubernetesconfiguration.aio.operations.ClusterExtensionTypeOperations - :ivar cluster_extension_types: ClusterExtensionTypesOperations operations - :vartype cluster_extension_types: azure.mgmt.kubernetesconfiguration.aio.operations.ClusterExtensionTypesOperations - :ivar extension_type_versions: ExtensionTypeVersionsOperations operations - :vartype extension_type_versions: azure.mgmt.kubernetesconfiguration.aio.operations.ExtensionTypeVersionsOperations - :ivar location_extension_types: LocationExtensionTypesOperations operations - :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.aio.operations.LocationExtensionTypesOperations - :ivar source_control_configurations: SourceControlConfigurationsOperations operations - :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.aio.operations.SourceControlConfigurationsOperations - :ivar flux_configurations: FluxConfigurationsOperations operations - :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigurationsOperations - :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations - :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.aio.operations.FluxConfigOperationStatusOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.kubernetesconfiguration.aio.operations.Operations + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str - :param str base_url: Service URL + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ + DEFAULT_API_VERSION = '2021-03-01' + _PROFILE_TAG = "azure.mgmt.kubernetesconfiguration.SourceControlConfigurationClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, + api_version: Optional[str] = None, base_url: Optional[str] = None, - **kwargs: Any + profile: KnownProfiles = KnownProfiles.default, + **kwargs # type: Any ) -> None: if not base_url: base_url = 'https://management.azure.com' self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(SourceControlConfigurationClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False - self._deserialize = Deserializer(client_models) - - self.extensions = ExtensionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operation_status = OperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize) - self.cluster_extension_type = ClusterExtensionTypeOperations( - self._client, self._config, self._serialize, self._deserialize) - self.cluster_extension_types = ClusterExtensionTypesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.extension_type_versions = ExtensionTypeVersionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.location_extension_types = LocationExtensionTypesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.source_control_configurations = SourceControlConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.flux_configurations = FluxConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.flux_config_operation_status = FluxConfigOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: - """Runs the network request through the client's chained policies. - - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + * 2020-07-01-preview: :mod:`v2020_07_01_preview.models` + * 2020-10-01-preview: :mod:`v2020_10_01_preview.models` + * 2021-03-01: :mod:`v2021_03_01.models` + * 2021-05-01-preview: :mod:`v2021_05_01_preview.models` + * 2021-06-01-preview: :mod:`v2021_06_01_preview.models` """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response - - async def close(self) -> None: - await self._client.close() + if api_version == '2020-07-01-preview': + from ..v2020_07_01_preview import models + return models + elif api_version == '2020-10-01-preview': + from ..v2020_10_01_preview import models + return models + elif api_version == '2021-03-01': + from ..v2021_03_01 import models + return models + elif api_version == '2021-05-01-preview': + from ..v2021_05_01_preview import models + return models + elif api_version == '2021-06-01-preview': + from ..v2021_06_01_preview import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def cluster_extension_type(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ClusterExtensionTypeOperations` + """ + api_version = self._get_api_version('cluster_extension_type') + if api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import ClusterExtensionTypeOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'cluster_extension_type'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def cluster_extension_types(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ClusterExtensionTypesOperations` + """ + api_version = self._get_api_version('cluster_extension_types') + if api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import ClusterExtensionTypesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'cluster_extension_types'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def extension_type_versions(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ExtensionTypeVersionsOperations` + """ + api_version = self._get_api_version('extension_type_versions') + if api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import ExtensionTypeVersionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'extension_type_versions'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def extensions(self): + """Instance depends on the API version: + + * 2020-07-01-preview: :class:`ExtensionsOperations` + * 2021-05-01-preview: :class:`ExtensionsOperations` + """ + api_version = self._get_api_version('extensions') + if api_version == '2020-07-01-preview': + from ..v2020_07_01_preview.aio.operations import ExtensionsOperations as OperationClass + elif api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import ExtensionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'extensions'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def flux_config_operation_status(self): + """Instance depends on the API version: + + * 2021-06-01-preview: :class:`FluxConfigOperationStatusOperations` + """ + api_version = self._get_api_version('flux_config_operation_status') + if api_version == '2021-06-01-preview': + from ..v2021_06_01_preview.aio.operations import FluxConfigOperationStatusOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'flux_config_operation_status'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def flux_configurations(self): + """Instance depends on the API version: + + * 2021-06-01-preview: :class:`FluxConfigurationsOperations` + """ + api_version = self._get_api_version('flux_configurations') + if api_version == '2021-06-01-preview': + from ..v2021_06_01_preview.aio.operations import FluxConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'flux_configurations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def location_extension_types(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`LocationExtensionTypesOperations` + """ + api_version = self._get_api_version('location_extension_types') + if api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import LocationExtensionTypesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'location_extension_types'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def operation_status(self): + """Instance depends on the API version: - async def __aenter__(self) -> "SourceControlConfigurationClient": + * 2021-05-01-preview: :class:`OperationStatusOperations` + * 2021-06-01-preview: :class:`OperationStatusOperations` + """ + api_version = self._get_api_version('operation_status') + if api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import OperationStatusOperations as OperationClass + elif api_version == '2021-06-01-preview': + from ..v2021_06_01_preview.aio.operations import OperationStatusOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'operation_status'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def operations(self): + """Instance depends on the API version: + + * 2020-07-01-preview: :class:`Operations` + * 2020-10-01-preview: :class:`Operations` + * 2021-03-01: :class:`Operations` + * 2021-05-01-preview: :class:`Operations` + * 2021-06-01-preview: :class:`Operations` + """ + api_version = self._get_api_version('operations') + if api_version == '2020-07-01-preview': + from ..v2020_07_01_preview.aio.operations import Operations as OperationClass + elif api_version == '2020-10-01-preview': + from ..v2020_10_01_preview.aio.operations import Operations as OperationClass + elif api_version == '2021-03-01': + from ..v2021_03_01.aio.operations import Operations as OperationClass + elif api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import Operations as OperationClass + elif api_version == '2021-06-01-preview': + from ..v2021_06_01_preview.aio.operations import Operations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def source_control_configurations(self): + """Instance depends on the API version: + + * 2020-07-01-preview: :class:`SourceControlConfigurationsOperations` + * 2020-10-01-preview: :class:`SourceControlConfigurationsOperations` + * 2021-03-01: :class:`SourceControlConfigurationsOperations` + * 2021-05-01-preview: :class:`SourceControlConfigurationsOperations` + """ + api_version = self._get_api_version('source_control_configurations') + if api_version == '2020-07-01-preview': + from ..v2020_07_01_preview.aio.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2020-10-01-preview': + from ..v2020_10_01_preview.aio.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2021-03-01': + from ..v2021_03_01.aio.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2021-05-01-preview': + from ..v2021_05_01_preview.aio.operations import SourceControlConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'source_control_configurations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): await self._client.__aenter__() return self - - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details): await self._client.__aexit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py index ee01fecd439..07db19b318c 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py @@ -6,26 +6,10 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._extensions_operations import ExtensionsOperations -from ._operation_status_operations import OperationStatusOperations -from ._cluster_extension_type_operations import ClusterExtensionTypeOperations -from ._cluster_extension_types_operations import ClusterExtensionTypesOperations -from ._extension_type_versions_operations import ExtensionTypeVersionsOperations -from ._location_extension_types_operations import LocationExtensionTypesOperations from ._source_control_configurations_operations import SourceControlConfigurationsOperations -from ._flux_configurations_operations import FluxConfigurationsOperations -from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations from ._operations import Operations __all__ = [ - 'ExtensionsOperations', - 'OperationStatusOperations', - 'ClusterExtensionTypeOperations', - 'ClusterExtensionTypesOperations', - 'ExtensionTypeVersionsOperations', - 'LocationExtensionTypesOperations', 'SourceControlConfigurationsOperations', - 'FluxConfigurationsOperations', - 'FluxConfigOperationStatusOperations', 'Operations', ] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py index 3f6d205b105..abad6a97377 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py @@ -43,7 +43,7 @@ def __init__(self, client, config, serializer, deserializer) -> None: def list( self, - **kwargs: Any + **kwargs ) -> AsyncIterable["_models.ResourceProviderOperationList"]: """List all the available operations the KubernetesConfiguration resource provider supports. @@ -57,7 +57,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2020-10-01-preview" accept = "application/json" def prepare_request(next_link=None): @@ -93,9 +93,8 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py index cc32dad8348..2a8fe57a0cf 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py @@ -50,11 +50,11 @@ async def get( cluster_resource_name: Union[str, "_models.Enum1"], cluster_name: str, source_control_configuration_name: str, - **kwargs: Any + **kwargs ) -> "_models.SourceControlConfiguration": """Gets details of the Source Control Configuration. - :param resource_group_name: The name of the resource group. The name is case insensitive. + :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). @@ -76,14 +76,14 @@ async def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-05-01-preview" + api_version = "2020-10-01-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), @@ -105,7 +105,7 @@ async def get( if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) @@ -124,11 +124,11 @@ async def create_or_update( cluster_name: str, source_control_configuration_name: str, source_control_configuration: "_models.SourceControlConfiguration", - **kwargs: Any + **kwargs ) -> "_models.SourceControlConfiguration": """Create a new Kubernetes Source Control Configuration. - :param resource_group_name: The name of the resource group. The name is case insensitive. + :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). @@ -152,15 +152,15 @@ async def create_or_update( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-05-01-preview" + api_version = "2020-10-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), @@ -186,7 +186,7 @@ async def create_or_update( if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: @@ -208,21 +208,21 @@ async def _delete_initial( cluster_resource_name: Union[str, "_models.Enum1"], cluster_name: str, source_control_configuration_name: str, - **kwargs: Any + **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-05-01-preview" + api_version = "2020-10-01-preview" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), @@ -244,7 +244,7 @@ async def _delete_initial( if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: @@ -259,12 +259,12 @@ async def begin_delete( cluster_resource_name: Union[str, "_models.Enum1"], cluster_name: str, source_control_configuration_name: str, - **kwargs: Any + **kwargs ) -> AsyncLROPoller[None]: """This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. - :param resource_group_name: The name of the resource group. The name is case insensitive. + :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). @@ -278,8 +278,8 @@ async def begin_delete( :type source_control_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) @@ -312,8 +312,8 @@ def get_long_running_output(pipeline_response): return cls(pipeline_response, None, {}) path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), @@ -340,11 +340,11 @@ def list( cluster_rp: Union[str, "_models.Enum0"], cluster_resource_name: Union[str, "_models.Enum1"], cluster_name: str, - **kwargs: Any + **kwargs ) -> AsyncIterable["_models.SourceControlConfigurationList"]: """List all Source Control Configurations. - :param resource_group_name: The name of the resource group. The name is case insensitive. + :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). @@ -364,7 +364,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-05-01-preview" + api_version = "2020-10-01-preview" accept = "application/json" def prepare_request(next_link=None): @@ -376,8 +376,8 @@ def prepare_request(next_link=None): # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), @@ -408,7 +408,7 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/models.py new file mode 100644 index 00000000000..64ec94156d5 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/models.py @@ -0,0 +1,7 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from .v2021_03_01.models import * diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/__init__.py new file mode 100644 index 00000000000..f13062376d7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/__init__.py @@ -0,0 +1,19 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['SourceControlConfigurationClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_configuration.py new file mode 100644 index 00000000000..89bdc90391d --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_configuration.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2020-07-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py new file mode 100644 index 00000000000..71f3974f333 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py @@ -0,0 +1,99 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from .operations import ExtensionsOperations +from . import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.operations.Operations + :ivar extensions: ExtensionsOperations operations + :vartype extensions: azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.operations.ExtensionsOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.extensions = ExtensionsOperations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> SourceControlConfigurationClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_version.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_version.py new file mode 100644 index 00000000000..e5754a47ce6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_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/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/__init__.py new file mode 100644 index 00000000000..ba52c91a7ba --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/__init__.py @@ -0,0 +1,10 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +__all__ = ['SourceControlConfigurationClient'] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_configuration.py new file mode 100644 index 00000000000..e15dc551cae --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2020-07-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py new file mode 100644 index 00000000000..a03dc102973 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py @@ -0,0 +1,92 @@ +# 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, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from .operations import ExtensionsOperations +from .. import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.aio.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.aio.operations.Operations + :ivar extensions: ExtensionsOperations operations + :vartype extensions: azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.aio.operations.ExtensionsOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + :param str base_url: Service URL + :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: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.extensions = ExtensionsOperations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "SourceControlConfigurationClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py new file mode 100644 index 00000000000..2e68d5ecb0c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py @@ -0,0 +1,17 @@ +# 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 ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations +from ._extensions_operations import ExtensionsOperations + +__all__ = [ + 'SourceControlConfigurationsOperations', + 'Operations', + 'ExtensionsOperations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py new file mode 100644 index 00000000000..e92980035ad --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py @@ -0,0 +1,433 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class ExtensionsOperations: + """ExtensionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def create( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_instance_name: str, + extension_instance: "_models.ExtensionInstance", + **kwargs: Any + ) -> "_models.ExtensionInstance": + """Create a new Kubernetes Cluster Extension Instance. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :param extension_instance: Properties necessary to Create an Extension Instance. + :type extension_instance: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionInstance, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstance"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(extension_instance, 'ExtensionInstance') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionInstance', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_instance_name: str, + **kwargs: Any + ) -> "_models.ExtensionInstance": + """Gets details of the Kubernetes Cluster Extension Instance. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionInstance, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstance"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionInstance', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + async def update( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_instance_name: str, + extension_instance: "_models.ExtensionInstanceUpdate", + **kwargs: Any + ) -> "_models.ExtensionInstance": + """Update an existing Kubernetes Cluster Extension Instance. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :param extension_instance: Properties to Update in the Extension Instance. + :type extension_instance: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstanceUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionInstance, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstance"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(extension_instance, 'ExtensionInstanceUpdate') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionInstance', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + async def delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + extension_instance_name: str, + **kwargs: Any + ) -> None: + """Delete a Kubernetes Cluster Extension Instance. This will cause the Agent to Uninstall the + extension instance from the cluster. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None, or the result of cls(response) + :rtype: None + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self.delete.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.ExtensionInstancesList"]: + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionInstancesList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstancesList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstancesList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionInstancesList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py new file mode 100644 index 00000000000..b9e2205f961 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py @@ -0,0 +1,105 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ResourceProviderOperationList"]: + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..116ecb3713e --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py @@ -0,0 +1,420 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations: + """SourceControlConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def create_or_update( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + source_control_configuration: "_models.SourceControlConfiguration", + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.SourceControlConfigurationList"]: + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/__init__.py new file mode 100644 index 00000000000..5d3f8aea197 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/__init__.py @@ -0,0 +1,99 @@ +# 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. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import ComplianceStatus + from ._models_py3 import ConfigurationIdentity + from ._models_py3 import ErrorDefinition + from ._models_py3 import ErrorResponse + from ._models_py3 import ExtensionInstance + from ._models_py3 import ExtensionInstanceUpdate + from ._models_py3 import ExtensionInstancesList + from ._models_py3 import ExtensionStatus + from ._models_py3 import HelmOperatorProperties + from ._models_py3 import ProxyResource + from ._models_py3 import Resource + from ._models_py3 import ResourceProviderOperation + from ._models_py3 import ResourceProviderOperationDisplay + from ._models_py3 import ResourceProviderOperationList + from ._models_py3 import Result + from ._models_py3 import Scope + from ._models_py3 import ScopeCluster + from ._models_py3 import ScopeNamespace + from ._models_py3 import SourceControlConfiguration + from ._models_py3 import SourceControlConfigurationList + from ._models_py3 import SystemData +except (SyntaxError, ImportError): + from ._models import ComplianceStatus # type: ignore + from ._models import ConfigurationIdentity # type: ignore + from ._models import ErrorDefinition # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import ExtensionInstance # type: ignore + from ._models import ExtensionInstanceUpdate # type: ignore + from ._models import ExtensionInstancesList # type: ignore + from ._models import ExtensionStatus # type: ignore + from ._models import HelmOperatorProperties # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import Resource # type: ignore + from ._models import ResourceProviderOperation # type: ignore + from ._models import ResourceProviderOperationDisplay # type: ignore + from ._models import ResourceProviderOperationList # type: ignore + from ._models import Result # type: ignore + from ._models import Scope # type: ignore + from ._models import ScopeCluster # type: ignore + from ._models import ScopeNamespace # type: ignore + from ._models import SourceControlConfiguration # type: ignore + from ._models import SourceControlConfigurationList # type: ignore + from ._models import SystemData # type: ignore + +from ._source_control_configuration_client_enums import ( + ComplianceStateType, + Enum0, + Enum1, + InstallStateType, + LevelType, + MessageLevelType, + OperatorScopeType, + OperatorType, + ProvisioningStateType, + ResourceIdentityType, +) + +__all__ = [ + 'ComplianceStatus', + 'ConfigurationIdentity', + 'ErrorDefinition', + 'ErrorResponse', + 'ExtensionInstance', + 'ExtensionInstanceUpdate', + 'ExtensionInstancesList', + 'ExtensionStatus', + 'HelmOperatorProperties', + 'ProxyResource', + 'Resource', + 'ResourceProviderOperation', + 'ResourceProviderOperationDisplay', + 'ResourceProviderOperationList', + 'Result', + 'Scope', + 'ScopeCluster', + 'ScopeNamespace', + 'SourceControlConfiguration', + 'SourceControlConfigurationList', + 'SystemData', + 'ComplianceStateType', + 'Enum0', + 'Enum1', + 'InstallStateType', + 'LevelType', + 'MessageLevelType', + 'OperatorScopeType', + 'OperatorType', + 'ProvisioningStateType', + 'ResourceIdentityType', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py new file mode 100644 index 00000000000..ef31b453ddc --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py @@ -0,0 +1,817 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = kwargs.get('last_config_applied', None) + self.message = kwargs.get('message', None) + self.message_level = kwargs.get('message_level', None) + + +class ConfigurationIdentity(msrest.serialization.Model): + """Identity for the managed cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of the system assigned identity which is used by the + configuration. + :vartype principal_id: str + :ivar tenant_id: The tenant id of the system assigned identity which is used by the + configuration. + :vartype tenant_id: str + :param type: The type of identity used for the configuration. Type 'SystemAssigned' will use an + implicitly created identity. Type 'None' will not use Managed Identity for the configuration. + Possible values include: "SystemAssigned", "None". + :type type: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceIdentityType + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ConfigurationIdentity, self).__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = kwargs.get('type', None) + + +class ErrorDefinition(msrest.serialization.Model): + """Error definition. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. Service specific error code which serves as the substatus for the HTTP + error code. + :type code: str + :param message: Required. Description of the error. + :type message: str + """ + + _validation = { + 'code': {'required': True}, + 'message': {'required': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorDefinition, self).__init__(**kwargs) + self.code = kwargs['code'] + self.message = kwargs['message'] + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: Error definition. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ErrorDefinition + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = None + + +class Resource(msrest.serialization.Model): + """The Resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = kwargs.get('system_data', None) + + +class ProxyResource(Resource): + """ARM proxy resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class ExtensionInstance(ProxyResource): + """The Extension Instance object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + :param extension_type: Type of the Extension, of which this resource is an instance of. It + must be one of the Extension Types registered with Microsoft.KubernetesConfiguration by the + Extension publisher. + :type extension_type: str + :param auto_upgrade_minor_version: Flag to note if this instance participates in auto upgrade + of minor version, or not. + :type auto_upgrade_minor_version: bool + :param release_train: ReleaseTrain this extension instance participates in for auto-upgrade + (e.g. Stable, Preview, etc.) - only if autoUpgradeMinorVersion is 'true'. + :type release_train: str + :param version: Version of the extension for this extension instance, if it is 'pinned' to a + specific version. autoUpgradeMinorVersion must be 'false'. + :type version: str + :param scope: Scope at which the extension instance is installed. + :type scope: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Scope + :param configuration_settings: Configuration settings, as name-value pairs for configuring this + instance of the extension. + :type configuration_settings: dict[str, str] + :param configuration_protected_settings: Configuration settings that are sensitive, as + name-value pairs for configuring this instance of the extension. + :type configuration_protected_settings: dict[str, str] + :ivar install_state: Status of installation of this instance of the extension. Possible values + include: "Pending", "Installed", "Failed". + :vartype install_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.InstallStateType + :param statuses: Status from this instance of the extension. + :type statuses: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionStatus] + :ivar creation_time: DateLiteral (per ISO8601) noting the time the resource was created by the + client (user). + :vartype creation_time: str + :ivar last_modified_time: DateLiteral (per ISO8601) noting the time the resource was modified + by the client (user). + :vartype last_modified_time: str + :ivar last_status_time: DateLiteral (per ISO8601) noting the time of last status from the + agent. + :vartype last_status_time: str + :ivar error_info: Error information from the Agent - e.g. errors during installation. + :vartype error_info: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ErrorDefinition + :param identity: The identity of the configuration. + :type identity: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ConfigurationIdentity + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'install_state': {'readonly': True}, + 'creation_time': {'readonly': True}, + 'last_modified_time': {'readonly': True}, + 'last_status_time': {'readonly': True}, + 'error_info': {'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'}, + 'extension_type': {'key': 'properties.extensionType', 'type': 'str'}, + 'auto_upgrade_minor_version': {'key': 'properties.autoUpgradeMinorVersion', 'type': 'bool'}, + 'release_train': {'key': 'properties.releaseTrain', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'scope': {'key': 'properties.scope', 'type': 'Scope'}, + 'configuration_settings': {'key': 'properties.configurationSettings', 'type': '{str}'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'install_state': {'key': 'properties.installState', 'type': 'str'}, + 'statuses': {'key': 'properties.statuses', 'type': '[ExtensionStatus]'}, + 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, + 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'str'}, + 'last_status_time': {'key': 'properties.lastStatusTime', 'type': 'str'}, + 'error_info': {'key': 'properties.errorInfo', 'type': 'ErrorDefinition'}, + 'identity': {'key': 'properties.identity', 'type': 'ConfigurationIdentity'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionInstance, self).__init__(**kwargs) + self.extension_type = kwargs.get('extension_type', None) + self.auto_upgrade_minor_version = kwargs.get('auto_upgrade_minor_version', None) + self.release_train = kwargs.get('release_train', "Stable") + self.version = kwargs.get('version', None) + self.scope = kwargs.get('scope', None) + self.configuration_settings = kwargs.get('configuration_settings', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.install_state = None + self.statuses = kwargs.get('statuses', None) + self.creation_time = None + self.last_modified_time = None + self.last_status_time = None + self.error_info = None + self.identity = kwargs.get('identity', None) + + +class ExtensionInstancesList(msrest.serialization.Model): + """Result of the request to list Extension Instances. It contains a list of ExtensionInstance objects and a 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 Extension Instances within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance] + :ivar next_link: URL to get the next set of extension instance objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ExtensionInstance]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionInstancesList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ExtensionInstanceUpdate(msrest.serialization.Model): + """Update Extension Instance request object. + + :param auto_upgrade_minor_version: Flag to note if this instance participates in Extension + Lifecycle Management or not. + :type auto_upgrade_minor_version: bool + :param release_train: ReleaseTrain this extension instance participates in for auto-upgrade + (e.g. Stable, Preview, etc.) - only if autoUpgradeMinorVersion is 'true'. + :type release_train: str + :param version: Version number of extension, to 'pin' to a specific version. + autoUpgradeMinorVersion must be 'false'. + :type version: str + """ + + _attribute_map = { + 'auto_upgrade_minor_version': {'key': 'properties.autoUpgradeMinorVersion', 'type': 'bool'}, + 'release_train': {'key': 'properties.releaseTrain', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionInstanceUpdate, self).__init__(**kwargs) + self.auto_upgrade_minor_version = kwargs.get('auto_upgrade_minor_version', None) + self.release_train = kwargs.get('release_train', "Stable") + self.version = kwargs.get('version', None) + + +class ExtensionStatus(msrest.serialization.Model): + """Status from this instance of the extension. + + :param code: Status code provided by the Extension. + :type code: str + :param display_status: Short description of status of this instance of the extension. + :type display_status: str + :param level: Level of the status. Possible values include: "Error", "Warning", "Information". + Default value: "Information". + :type level: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.LevelType + :param message: Detailed message of the status from the Extension instance. + :type message: str + :param time: DateLiteral (per ISO8601) noting the time of installation status. + :type time: str + """ + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'display_status': {'key': 'displayStatus', 'type': 'str'}, + 'level': {'key': 'level', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'time': {'key': 'time', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionStatus, self).__init__(**kwargs) + self.code = kwargs.get('code', None) + self.display_status = kwargs.get('display_status', None) + self.level = kwargs.get('level', "Information") + self.message = kwargs.get('message', None) + self.time = kwargs.get('time', None) + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = kwargs.get('chart_version', None) + self.chart_values = kwargs.get('chart_values', None) + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceProviderOperationDisplay + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.display = kwargs.get('display', None) + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = kwargs.get('provider', None) + self.resource = kwargs.get('resource', None) + self.operation = kwargs.get('operation', None) + self.description = kwargs.get('description', None) + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = None + + +class Result(msrest.serialization.Model): + """Sample result definition. + + :param sample_property: Sample property of type string. + :type sample_property: str + """ + + _attribute_map = { + 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Result, self).__init__(**kwargs) + self.sample_property = kwargs.get('sample_property', None) + + +class Scope(msrest.serialization.Model): + """Scope of the extensionInstance. It can be either Cluster or Namespace; but not both. + + :param cluster: Specifies that the scope of the extensionInstance is Cluster. + :type cluster: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ScopeCluster + :param namespace: Specifies that the scope of the extensionInstance is Namespace. + :type namespace: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ScopeNamespace + """ + + _attribute_map = { + 'cluster': {'key': 'cluster', 'type': 'ScopeCluster'}, + 'namespace': {'key': 'namespace', 'type': 'ScopeNamespace'}, + } + + def __init__( + self, + **kwargs + ): + super(Scope, self).__init__(**kwargs) + self.cluster = kwargs.get('cluster', None) + self.namespace = kwargs.get('namespace', None) + + +class ScopeCluster(msrest.serialization.Model): + """Specifies that the scope of the extensionInstance is Cluster. + + :param release_namespace: Namespace where the extension Release must be placed, for a Cluster + scoped extensionInstance. If this namespace does not exist, it will be created. + :type release_namespace: str + """ + + _attribute_map = { + 'release_namespace': {'key': 'releaseNamespace', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ScopeCluster, self).__init__(**kwargs) + self.release_namespace = kwargs.get('release_namespace', None) + + +class ScopeNamespace(msrest.serialization.Model): + """Specifies that the scope of the extensionInstance is Namespace. + + :param target_namespace: Namespace where the extensionInstance will be created for an Namespace + scoped extensionInstance. If this namespace does not exist, it will be created. + :type target_namespace: str + """ + + _attribute_map = { + 'target_namespace': {'key': 'targetNamespace', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ScopeNamespace, self).__init__(**kwargs) + self.target_namespace = kwargs.get('target_namespace', None) + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(**kwargs) + self.repository_url = kwargs.get('repository_url', None) + self.operator_namespace = kwargs.get('operator_namespace', "default") + self.operator_instance_name = kwargs.get('operator_instance_name', None) + self.operator_type = kwargs.get('operator_type', None) + self.operator_params = kwargs.get('operator_params', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.operator_scope = kwargs.get('operator_scope', "cluster") + self.repository_public_key = None + self.ssh_known_hosts_contents = kwargs.get('ssh_known_hosts_contents', None) + self.enable_helm_operator = kwargs.get('enable_helm_operator', None) + self.helm_operator_properties = kwargs.get('helm_operator_properties', None) + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar created_by: A string identifier for the identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource: user, application, + managedIdentity, key. + :vartype created_by_type: str + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: A string identifier for 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: user, + application, managedIdentity, key. + :vartype last_modified_by_type: str + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _validation = { + 'created_by': {'readonly': True}, + 'created_by_type': {'readonly': True}, + 'created_at': {'readonly': True}, + 'last_modified_by': {'readonly': True}, + 'last_modified_by_type': {'readonly': True}, + 'last_modified_at': {'readonly': True}, + } + + _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, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = None + self.created_by_type = None + self.created_at = None + self.last_modified_by = None + self.last_modified_by_type = None + self.last_modified_at = None diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py new file mode 100644 index 00000000000..7d8c10c5306 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py @@ -0,0 +1,890 @@ +# 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 datetime +from typing import Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._source_control_configuration_client_enums import * + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + *, + last_config_applied: Optional[datetime.datetime] = None, + message: Optional[str] = None, + message_level: Optional[Union[str, "MessageLevelType"]] = None, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = last_config_applied + self.message = message + self.message_level = message_level + + +class ConfigurationIdentity(msrest.serialization.Model): + """Identity for the managed cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of the system assigned identity which is used by the + configuration. + :vartype principal_id: str + :ivar tenant_id: The tenant id of the system assigned identity which is used by the + configuration. + :vartype tenant_id: str + :param type: The type of identity used for the configuration. Type 'SystemAssigned' will use an + implicitly created identity. Type 'None' will not use Managed Identity for the configuration. + Possible values include: "SystemAssigned", "None". + :type type: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceIdentityType + """ + + _validation = { + 'principal_id': {'readonly': True}, + 'tenant_id': {'readonly': True}, + } + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + type: Optional[Union[str, "ResourceIdentityType"]] = None, + **kwargs + ): + super(ConfigurationIdentity, self).__init__(**kwargs) + self.principal_id = None + self.tenant_id = None + self.type = type + + +class ErrorDefinition(msrest.serialization.Model): + """Error definition. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. Service specific error code which serves as the substatus for the HTTP + error code. + :type code: str + :param message: Required. Description of the error. + :type message: str + """ + + _validation = { + 'code': {'required': True}, + 'message': {'required': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + *, + code: str, + message: str, + **kwargs + ): + super(ErrorDefinition, self).__init__(**kwargs) + self.code = code + self.message = message + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: Error definition. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ErrorDefinition + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = None + + +class Resource(msrest.serialization.Model): + """The Resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + *, + system_data: Optional["SystemData"] = None, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = system_data + + +class ProxyResource(Resource): + """ARM proxy resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + *, + system_data: Optional["SystemData"] = None, + **kwargs + ): + super(ProxyResource, self).__init__(system_data=system_data, **kwargs) + + +class ExtensionInstance(ProxyResource): + """The Extension Instance object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + :param extension_type: Type of the Extension, of which this resource is an instance of. It + must be one of the Extension Types registered with Microsoft.KubernetesConfiguration by the + Extension publisher. + :type extension_type: str + :param auto_upgrade_minor_version: Flag to note if this instance participates in auto upgrade + of minor version, or not. + :type auto_upgrade_minor_version: bool + :param release_train: ReleaseTrain this extension instance participates in for auto-upgrade + (e.g. Stable, Preview, etc.) - only if autoUpgradeMinorVersion is 'true'. + :type release_train: str + :param version: Version of the extension for this extension instance, if it is 'pinned' to a + specific version. autoUpgradeMinorVersion must be 'false'. + :type version: str + :param scope: Scope at which the extension instance is installed. + :type scope: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Scope + :param configuration_settings: Configuration settings, as name-value pairs for configuring this + instance of the extension. + :type configuration_settings: dict[str, str] + :param configuration_protected_settings: Configuration settings that are sensitive, as + name-value pairs for configuring this instance of the extension. + :type configuration_protected_settings: dict[str, str] + :ivar install_state: Status of installation of this instance of the extension. Possible values + include: "Pending", "Installed", "Failed". + :vartype install_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.InstallStateType + :param statuses: Status from this instance of the extension. + :type statuses: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionStatus] + :ivar creation_time: DateLiteral (per ISO8601) noting the time the resource was created by the + client (user). + :vartype creation_time: str + :ivar last_modified_time: DateLiteral (per ISO8601) noting the time the resource was modified + by the client (user). + :vartype last_modified_time: str + :ivar last_status_time: DateLiteral (per ISO8601) noting the time of last status from the + agent. + :vartype last_status_time: str + :ivar error_info: Error information from the Agent - e.g. errors during installation. + :vartype error_info: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ErrorDefinition + :param identity: The identity of the configuration. + :type identity: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ConfigurationIdentity + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'install_state': {'readonly': True}, + 'creation_time': {'readonly': True}, + 'last_modified_time': {'readonly': True}, + 'last_status_time': {'readonly': True}, + 'error_info': {'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'}, + 'extension_type': {'key': 'properties.extensionType', 'type': 'str'}, + 'auto_upgrade_minor_version': {'key': 'properties.autoUpgradeMinorVersion', 'type': 'bool'}, + 'release_train': {'key': 'properties.releaseTrain', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + 'scope': {'key': 'properties.scope', 'type': 'Scope'}, + 'configuration_settings': {'key': 'properties.configurationSettings', 'type': '{str}'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'install_state': {'key': 'properties.installState', 'type': 'str'}, + 'statuses': {'key': 'properties.statuses', 'type': '[ExtensionStatus]'}, + 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, + 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'str'}, + 'last_status_time': {'key': 'properties.lastStatusTime', 'type': 'str'}, + 'error_info': {'key': 'properties.errorInfo', 'type': 'ErrorDefinition'}, + 'identity': {'key': 'properties.identity', 'type': 'ConfigurationIdentity'}, + } + + def __init__( + self, + *, + system_data: Optional["SystemData"] = None, + extension_type: Optional[str] = None, + auto_upgrade_minor_version: Optional[bool] = None, + release_train: Optional[str] = "Stable", + version: Optional[str] = None, + scope: Optional["Scope"] = None, + configuration_settings: Optional[Dict[str, str]] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + statuses: Optional[List["ExtensionStatus"]] = None, + identity: Optional["ConfigurationIdentity"] = None, + **kwargs + ): + super(ExtensionInstance, self).__init__(system_data=system_data, **kwargs) + self.extension_type = extension_type + self.auto_upgrade_minor_version = auto_upgrade_minor_version + self.release_train = release_train + self.version = version + self.scope = scope + self.configuration_settings = configuration_settings + self.configuration_protected_settings = configuration_protected_settings + self.install_state = None + self.statuses = statuses + self.creation_time = None + self.last_modified_time = None + self.last_status_time = None + self.error_info = None + self.identity = identity + + +class ExtensionInstancesList(msrest.serialization.Model): + """Result of the request to list Extension Instances. It contains a list of ExtensionInstance objects and a 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 Extension Instances within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance] + :ivar next_link: URL to get the next set of extension instance objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ExtensionInstance]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ExtensionInstancesList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class ExtensionInstanceUpdate(msrest.serialization.Model): + """Update Extension Instance request object. + + :param auto_upgrade_minor_version: Flag to note if this instance participates in Extension + Lifecycle Management or not. + :type auto_upgrade_minor_version: bool + :param release_train: ReleaseTrain this extension instance participates in for auto-upgrade + (e.g. Stable, Preview, etc.) - only if autoUpgradeMinorVersion is 'true'. + :type release_train: str + :param version: Version number of extension, to 'pin' to a specific version. + autoUpgradeMinorVersion must be 'false'. + :type version: str + """ + + _attribute_map = { + 'auto_upgrade_minor_version': {'key': 'properties.autoUpgradeMinorVersion', 'type': 'bool'}, + 'release_train': {'key': 'properties.releaseTrain', 'type': 'str'}, + 'version': {'key': 'properties.version', 'type': 'str'}, + } + + def __init__( + self, + *, + auto_upgrade_minor_version: Optional[bool] = None, + release_train: Optional[str] = "Stable", + version: Optional[str] = None, + **kwargs + ): + super(ExtensionInstanceUpdate, self).__init__(**kwargs) + self.auto_upgrade_minor_version = auto_upgrade_minor_version + self.release_train = release_train + self.version = version + + +class ExtensionStatus(msrest.serialization.Model): + """Status from this instance of the extension. + + :param code: Status code provided by the Extension. + :type code: str + :param display_status: Short description of status of this instance of the extension. + :type display_status: str + :param level: Level of the status. Possible values include: "Error", "Warning", "Information". + Default value: "Information". + :type level: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.LevelType + :param message: Detailed message of the status from the Extension instance. + :type message: str + :param time: DateLiteral (per ISO8601) noting the time of installation status. + :type time: str + """ + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'display_status': {'key': 'displayStatus', 'type': 'str'}, + 'level': {'key': 'level', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'time': {'key': 'time', 'type': 'str'}, + } + + def __init__( + self, + *, + code: Optional[str] = None, + display_status: Optional[str] = None, + level: Optional[Union[str, "LevelType"]] = "Information", + message: Optional[str] = None, + time: Optional[str] = None, + **kwargs + ): + super(ExtensionStatus, self).__init__(**kwargs) + self.code = code + self.display_status = display_status + self.level = level + self.message = message + self.time = time + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + *, + chart_version: Optional[str] = None, + chart_values: Optional[str] = None, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = chart_version + self.chart_values = chart_values + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceProviderOperationDisplay + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["ResourceProviderOperationDisplay"] = None, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = name + self.display = display + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _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, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["ResourceProviderOperation"]] = None, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = value + self.next_link = None + + +class Result(msrest.serialization.Model): + """Sample result definition. + + :param sample_property: Sample property of type string. + :type sample_property: str + """ + + _attribute_map = { + 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, + } + + def __init__( + self, + *, + sample_property: Optional[str] = None, + **kwargs + ): + super(Result, self).__init__(**kwargs) + self.sample_property = sample_property + + +class Scope(msrest.serialization.Model): + """Scope of the extensionInstance. It can be either Cluster or Namespace; but not both. + + :param cluster: Specifies that the scope of the extensionInstance is Cluster. + :type cluster: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ScopeCluster + :param namespace: Specifies that the scope of the extensionInstance is Namespace. + :type namespace: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ScopeNamespace + """ + + _attribute_map = { + 'cluster': {'key': 'cluster', 'type': 'ScopeCluster'}, + 'namespace': {'key': 'namespace', 'type': 'ScopeNamespace'}, + } + + def __init__( + self, + *, + cluster: Optional["ScopeCluster"] = None, + namespace: Optional["ScopeNamespace"] = None, + **kwargs + ): + super(Scope, self).__init__(**kwargs) + self.cluster = cluster + self.namespace = namespace + + +class ScopeCluster(msrest.serialization.Model): + """Specifies that the scope of the extensionInstance is Cluster. + + :param release_namespace: Namespace where the extension Release must be placed, for a Cluster + scoped extensionInstance. If this namespace does not exist, it will be created. + :type release_namespace: str + """ + + _attribute_map = { + 'release_namespace': {'key': 'releaseNamespace', 'type': 'str'}, + } + + def __init__( + self, + *, + release_namespace: Optional[str] = None, + **kwargs + ): + super(ScopeCluster, self).__init__(**kwargs) + self.release_namespace = release_namespace + + +class ScopeNamespace(msrest.serialization.Model): + """Specifies that the scope of the extensionInstance is Namespace. + + :param target_namespace: Namespace where the extensionInstance will be created for an Namespace + scoped extensionInstance. If this namespace does not exist, it will be created. + :type target_namespace: str + """ + + _attribute_map = { + 'target_namespace': {'key': 'targetNamespace', 'type': 'str'}, + } + + def __init__( + self, + *, + target_namespace: Optional[str] = None, + **kwargs + ): + super(ScopeNamespace, self).__init__(**kwargs) + self.target_namespace = target_namespace + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + *, + system_data: Optional["SystemData"] = None, + repository_url: Optional[str] = None, + operator_namespace: Optional[str] = "default", + operator_instance_name: Optional[str] = None, + operator_type: Optional[Union[str, "OperatorType"]] = None, + operator_params: Optional[str] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + operator_scope: Optional[Union[str, "OperatorScopeType"]] = "cluster", + ssh_known_hosts_contents: Optional[str] = None, + enable_helm_operator: Optional[bool] = None, + helm_operator_properties: Optional["HelmOperatorProperties"] = None, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(system_data=system_data, **kwargs) + self.repository_url = repository_url + self.operator_namespace = operator_namespace + self.operator_instance_name = operator_instance_name + self.operator_type = operator_type + self.operator_params = operator_params + self.configuration_protected_settings = configuration_protected_settings + self.operator_scope = operator_scope + self.repository_public_key = None + self.ssh_known_hosts_contents = ssh_known_hosts_contents + self.enable_helm_operator = enable_helm_operator + self.helm_operator_properties = helm_operator_properties + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar created_by: A string identifier for the identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource: user, application, + managedIdentity, key. + :vartype created_by_type: str + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: A string identifier for 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: user, + application, managedIdentity, key. + :vartype last_modified_by_type: str + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _validation = { + 'created_by': {'readonly': True}, + 'created_by_type': {'readonly': True}, + 'created_at': {'readonly': True}, + 'last_modified_by': {'readonly': True}, + 'last_modified_by_type': {'readonly': True}, + 'last_modified_at': {'readonly': True}, + } + + _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, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = None + self.created_by_type = None + self.created_at = None + self.last_modified_by = None + self.last_modified_by_type = None + self.last_modified_at = None diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py new file mode 100644 index 00000000000..825cfccadd1 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py @@ -0,0 +1,102 @@ +# 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, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class ComplianceStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The compliance state of the configuration. + """ + + PENDING = "Pending" + COMPLIANT = "Compliant" + NONCOMPLIANT = "Noncompliant" + INSTALLED = "Installed" + FAILED = "Failed" + +class Enum0(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MICROSOFT_CONTAINER_SERVICE = "Microsoft.ContainerService" + MICROSOFT_KUBERNETES = "Microsoft.Kubernetes" + +class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MANAGED_CLUSTERS = "managedClusters" + CONNECTED_CLUSTERS = "connectedClusters" + +class InstallStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Status of installation of this instance of the extension. + """ + + PENDING = "Pending" + INSTALLED = "Installed" + FAILED = "Failed" + +class LevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Level of the status. + """ + + ERROR = "Error" + WARNING = "Warning" + INFORMATION = "Information" + +class MessageLevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Level of the message. + """ + + ERROR = "Error" + WARNING = "Warning" + INFORMATION = "Information" + +class OperatorScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Scope at which the operator will be installed. + """ + + CLUSTER = "cluster" + NAMESPACE = "namespace" + +class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Type of the operator + """ + + FLUX = "Flux" + +class ProvisioningStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The provisioning state of the resource provider. + """ + + ACCEPTED = "Accepted" + DELETING = "Deleting" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + +class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The type of identity used for the configuration. Type 'SystemAssigned' will use an implicitly + created identity. Type 'None' will not use Managed Identity for the configuration. + """ + + SYSTEM_ASSIGNED = "SystemAssigned" + NONE = "None" diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/__init__.py new file mode 100644 index 00000000000..2e68d5ecb0c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/__init__.py @@ -0,0 +1,17 @@ +# 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 ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations +from ._extensions_operations import ExtensionsOperations + +__all__ = [ + 'SourceControlConfigurationsOperations', + 'Operations', + 'ExtensionsOperations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py new file mode 100644 index 00000000000..c3e2b0cf5f4 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py @@ -0,0 +1,442 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class ExtensionsOperations(object): + """ExtensionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def create( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_instance_name, # type: str + extension_instance, # type: "_models.ExtensionInstance" + **kwargs # type: Any + ): + # type: (...) -> "_models.ExtensionInstance" + """Create a new Kubernetes Cluster Extension Instance. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :param extension_instance: Properties necessary to Create an Extension Instance. + :type extension_instance: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionInstance, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstance"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(extension_instance, 'ExtensionInstance') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionInstance', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_instance_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.ExtensionInstance" + """Gets details of the Kubernetes Cluster Extension Instance. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionInstance, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstance"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionInstance', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + def update( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_instance_name, # type: str + extension_instance, # type: "_models.ExtensionInstanceUpdate" + **kwargs # type: Any + ): + # type: (...) -> "_models.ExtensionInstance" + """Update an existing Kubernetes Cluster Extension Instance. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :param extension_instance: Properties to Update in the Extension Instance. + :type extension_instance: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstanceUpdate + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ExtensionInstance, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstance + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstance"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(extension_instance, 'ExtensionInstanceUpdate') + body_content_kwargs['content'] = body_content + request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('ExtensionInstance', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + def delete( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + extension_instance_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + """Delete a Kubernetes Cluster Extension Instance. This will cause the Agent to Uninstall the + extension instance from the cluster. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param extension_instance_name: Name of an instance of the Extension. + :type extension_instance_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None, or the result of cls(response) + :rtype: None + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self.delete.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'extensionInstanceName': self._serialize.url("extension_instance_name", extension_instance_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions/{extensionInstanceName}'} # type: ignore + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ExtensionInstancesList"] + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ExtensionInstancesList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ExtensionInstancesList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionInstancesList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ExtensionInstancesList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/extensions'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_operations.py new file mode 100644 index 00000000000..1fe1fbf39b1 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_operations.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ResourceProviderOperationList"] + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..d192efa6d03 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py @@ -0,0 +1,429 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations(object): + """SourceControlConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def create_or_update( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + source_control_configuration, # type: "_models.SourceControlConfiguration" + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.SourceControlConfigurationList"] + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-07-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/__init__.py new file mode 100644 index 00000000000..f13062376d7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/__init__.py @@ -0,0 +1,19 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['SourceControlConfigurationClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_configuration.py new file mode 100644 index 00000000000..d5969e53212 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_configuration.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2020-10-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py new file mode 100644 index 00000000000..c079c472da6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py @@ -0,0 +1,94 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from . import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> SourceControlConfigurationClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_version.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_version.py new file mode 100644 index 00000000000..e5754a47ce6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_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/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/__init__.py new file mode 100644 index 00000000000..ba52c91a7ba --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/__init__.py @@ -0,0 +1,10 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +__all__ = ['SourceControlConfigurationClient'] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_configuration.py new file mode 100644 index 00000000000..8002c1a9fbc --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2020-10-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py new file mode 100644 index 00000000000..1e3021bd71a --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py @@ -0,0 +1,87 @@ +# 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, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from .. import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.aio.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.aio.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + :param str base_url: Service URL + :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: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "SourceControlConfigurationClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py new file mode 100644 index 00000000000..07db19b318c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations + +__all__ = [ + 'SourceControlConfigurationsOperations', + 'Operations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py new file mode 100644 index 00000000000..3f70e7e1e81 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py @@ -0,0 +1,105 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ResourceProviderOperationList"]: + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..52063acf78e --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py @@ -0,0 +1,420 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations: + """SourceControlConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def create_or_update( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + source_control_configuration: "_models.SourceControlConfiguration", + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.SourceControlConfigurationList"]: + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/__init__.py new file mode 100644 index 00000000000..b1e23c9e1d7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/__init__.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import ComplianceStatus + from ._models_py3 import ErrorDefinition + from ._models_py3 import ErrorResponse + from ._models_py3 import HelmOperatorProperties + from ._models_py3 import ProxyResource + from ._models_py3 import Resource + from ._models_py3 import ResourceProviderOperation + from ._models_py3 import ResourceProviderOperationDisplay + from ._models_py3 import ResourceProviderOperationList + from ._models_py3 import Result + from ._models_py3 import SourceControlConfiguration + from ._models_py3 import SourceControlConfigurationList + from ._models_py3 import SystemData +except (SyntaxError, ImportError): + from ._models import ComplianceStatus # type: ignore + from ._models import ErrorDefinition # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import HelmOperatorProperties # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import Resource # type: ignore + from ._models import ResourceProviderOperation # type: ignore + from ._models import ResourceProviderOperationDisplay # type: ignore + from ._models import ResourceProviderOperationList # type: ignore + from ._models import Result # type: ignore + from ._models import SourceControlConfiguration # type: ignore + from ._models import SourceControlConfigurationList # type: ignore + from ._models import SystemData # type: ignore + +from ._source_control_configuration_client_enums import ( + ComplianceStateType, + Enum0, + Enum1, + MessageLevelType, + OperatorScopeType, + OperatorType, + ProvisioningStateType, +) + +__all__ = [ + 'ComplianceStatus', + 'ErrorDefinition', + 'ErrorResponse', + 'HelmOperatorProperties', + 'ProxyResource', + 'Resource', + 'ResourceProviderOperation', + 'ResourceProviderOperationDisplay', + 'ResourceProviderOperationList', + 'Result', + 'SourceControlConfiguration', + 'SourceControlConfigurationList', + 'SystemData', + 'ComplianceStateType', + 'Enum0', + 'Enum1', + 'MessageLevelType', + 'OperatorScopeType', + 'OperatorType', + 'ProvisioningStateType', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models.py new file mode 100644 index 00000000000..12ebfd16f6d --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models.py @@ -0,0 +1,506 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = kwargs.get('last_config_applied', None) + self.message = kwargs.get('message', None) + self.message_level = kwargs.get('message_level', None) + + +class ErrorDefinition(msrest.serialization.Model): + """Error definition. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. Service specific error code which serves as the substatus for the HTTP + error code. + :type code: str + :param message: Required. Description of the error. + :type message: str + """ + + _validation = { + 'code': {'required': True}, + 'message': {'required': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorDefinition, self).__init__(**kwargs) + self.code = kwargs['code'] + self.message = kwargs['message'] + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: Error definition. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ErrorDefinition + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = None + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = kwargs.get('chart_version', None) + self.chart_values = kwargs.get('chart_values', None) + + +class Resource(msrest.serialization.Model): + """The Resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = kwargs.get('system_data', None) + + +class ProxyResource(Resource): + """ARM proxy resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ResourceProviderOperationDisplay + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.display = kwargs.get('display', None) + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = kwargs.get('provider', None) + self.resource = kwargs.get('resource', None) + self.operation = kwargs.get('operation', None) + self.description = kwargs.get('description', None) + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = None + + +class Result(msrest.serialization.Model): + """Sample result definition. + + :param sample_property: Sample property of type string. + :type sample_property: str + """ + + _attribute_map = { + 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Result, self).__init__(**kwargs) + self.sample_property = kwargs.get('sample_property', None) + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(**kwargs) + self.repository_url = kwargs.get('repository_url', None) + self.operator_namespace = kwargs.get('operator_namespace', "default") + self.operator_instance_name = kwargs.get('operator_instance_name', None) + self.operator_type = kwargs.get('operator_type', None) + self.operator_params = kwargs.get('operator_params', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.operator_scope = kwargs.get('operator_scope', "cluster") + self.repository_public_key = None + self.ssh_known_hosts_contents = kwargs.get('ssh_known_hosts_contents', None) + self.enable_helm_operator = kwargs.get('enable_helm_operator', None) + self.helm_operator_properties = kwargs.get('helm_operator_properties', None) + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar created_by: A string identifier for the identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource: user, application, + managedIdentity, key. + :vartype created_by_type: str + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: A string identifier for 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: user, + application, managedIdentity, key. + :vartype last_modified_by_type: str + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _validation = { + 'created_by': {'readonly': True}, + 'created_by_type': {'readonly': True}, + 'created_at': {'readonly': True}, + 'last_modified_by': {'readonly': True}, + 'last_modified_by_type': {'readonly': True}, + 'last_modified_at': {'readonly': True}, + } + + _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, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = None + self.created_by_type = None + self.created_at = None + self.last_modified_by = None + self.last_modified_by_type = None + self.last_modified_at = None diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models_py3.py new file mode 100644 index 00000000000..ed2e27c2b8f --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models_py3.py @@ -0,0 +1,549 @@ +# 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 datetime +from typing import Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._source_control_configuration_client_enums import * + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + *, + last_config_applied: Optional[datetime.datetime] = None, + message: Optional[str] = None, + message_level: Optional[Union[str, "MessageLevelType"]] = None, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = last_config_applied + self.message = message + self.message_level = message_level + + +class ErrorDefinition(msrest.serialization.Model): + """Error definition. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. Service specific error code which serves as the substatus for the HTTP + error code. + :type code: str + :param message: Required. Description of the error. + :type message: str + """ + + _validation = { + 'code': {'required': True}, + 'message': {'required': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + *, + code: str, + message: str, + **kwargs + ): + super(ErrorDefinition, self).__init__(**kwargs) + self.code = code + self.message = message + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: Error definition. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ErrorDefinition + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = None + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + *, + chart_version: Optional[str] = None, + chart_values: Optional[str] = None, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = chart_version + self.chart_values = chart_values + + +class Resource(msrest.serialization.Model): + """The Resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + *, + system_data: Optional["SystemData"] = None, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = system_data + + +class ProxyResource(Resource): + """ARM proxy resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SystemData + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + } + + def __init__( + self, + *, + system_data: Optional["SystemData"] = None, + **kwargs + ): + super(ProxyResource, self).__init__(system_data=system_data, **kwargs) + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ResourceProviderOperationDisplay + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["ResourceProviderOperationDisplay"] = None, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = name + self.display = display + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _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, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["ResourceProviderOperation"]] = None, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = value + self.next_link = None + + +class Result(msrest.serialization.Model): + """Sample result definition. + + :param sample_property: Sample property of type string. + :type sample_property: str + """ + + _attribute_map = { + 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, + } + + def __init__( + self, + *, + sample_property: Optional[str] = None, + **kwargs + ): + super(Result, self).__init__(**kwargs) + self.sample_property = sample_property + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :param system_data: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :type system_data: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + *, + system_data: Optional["SystemData"] = None, + repository_url: Optional[str] = None, + operator_namespace: Optional[str] = "default", + operator_instance_name: Optional[str] = None, + operator_type: Optional[Union[str, "OperatorType"]] = None, + operator_params: Optional[str] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + operator_scope: Optional[Union[str, "OperatorScopeType"]] = "cluster", + ssh_known_hosts_contents: Optional[str] = None, + enable_helm_operator: Optional[bool] = None, + helm_operator_properties: Optional["HelmOperatorProperties"] = None, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(system_data=system_data, **kwargs) + self.repository_url = repository_url + self.operator_namespace = operator_namespace + self.operator_instance_name = operator_instance_name + self.operator_type = operator_type + self.operator_params = operator_params + self.configuration_protected_settings = configuration_protected_settings + self.operator_scope = operator_scope + self.repository_public_key = None + self.ssh_known_hosts_contents = ssh_known_hosts_contents + self.enable_helm_operator = enable_helm_operator + self.helm_operator_properties = helm_operator_properties + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar created_by: A string identifier for the identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource: user, application, + managedIdentity, key. + :vartype created_by_type: str + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: A string identifier for 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: user, + application, managedIdentity, key. + :vartype last_modified_by_type: str + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _validation = { + 'created_by': {'readonly': True}, + 'created_by_type': {'readonly': True}, + 'created_at': {'readonly': True}, + 'last_modified_by': {'readonly': True}, + 'last_modified_by_type': {'readonly': True}, + 'last_modified_at': {'readonly': True}, + } + + _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, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = None + self.created_by_type = None + self.created_at = None + self.last_modified_by = None + self.last_modified_by_type = None + self.last_modified_at = None diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py new file mode 100644 index 00000000000..3803d916bfd --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py @@ -0,0 +1,78 @@ +# 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, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class ComplianceStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The compliance state of the configuration. + """ + + PENDING = "Pending" + COMPLIANT = "Compliant" + NONCOMPLIANT = "Noncompliant" + INSTALLED = "Installed" + FAILED = "Failed" + +class Enum0(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MICROSOFT_CONTAINER_SERVICE = "Microsoft.ContainerService" + MICROSOFT_KUBERNETES = "Microsoft.Kubernetes" + +class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MANAGED_CLUSTERS = "managedClusters" + CONNECTED_CLUSTERS = "connectedClusters" + +class MessageLevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Level of the message. + """ + + ERROR = "Error" + WARNING = "Warning" + INFORMATION = "Information" + +class OperatorScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Scope at which the operator will be installed. + """ + + CLUSTER = "cluster" + NAMESPACE = "namespace" + +class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Type of the operator + """ + + FLUX = "Flux" + +class ProvisioningStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The provisioning state of the resource provider. + """ + + ACCEPTED = "Accepted" + DELETING = "Deleting" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + FAILED = "Failed" diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/__init__.py new file mode 100644 index 00000000000..07db19b318c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations + +__all__ = [ + 'SourceControlConfigurationsOperations', + 'Operations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_operations.py new file mode 100644 index 00000000000..09bd96085f7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_operations.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ResourceProviderOperationList"] + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..fa926900038 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py @@ -0,0 +1,429 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations(object): + """SourceControlConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def create_or_update( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + source_control_configuration, # type: "_models.SourceControlConfiguration" + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.SourceControlConfigurationList"] + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2020_10_01_preview.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2020-10-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/__init__.py new file mode 100644 index 00000000000..f13062376d7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/__init__.py @@ -0,0 +1,19 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['SourceControlConfigurationClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_configuration.py new file mode 100644 index 00000000000..645328abb1f --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_configuration.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-03-01" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_source_control_configuration_client.py new file mode 100644 index 00000000000..50b673797b5 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_source_control_configuration_client.py @@ -0,0 +1,94 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from . import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2021_03_01.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2021_03_01.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> SourceControlConfigurationClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_version.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_version.py new file mode 100644 index 00000000000..e5754a47ce6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_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/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/__init__.py new file mode 100644 index 00000000000..ba52c91a7ba --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/__init__.py @@ -0,0 +1,10 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +__all__ = ['SourceControlConfigurationClient'] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_configuration.py new file mode 100644 index 00000000000..682d2762893 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-03-01" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py new file mode 100644 index 00000000000..2db9ca6cfeb --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py @@ -0,0 +1,87 @@ +# 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, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from .. import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2021_03_01.aio.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2021_03_01.aio.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). + :type subscription_id: str + :param str base_url: Service URL + :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: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "SourceControlConfigurationClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/__init__.py new file mode 100644 index 00000000000..07db19b318c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations + +__all__ = [ + 'SourceControlConfigurationsOperations', + 'Operations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_operations.py new file mode 100644 index 00000000000..09d8376d112 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_operations.py @@ -0,0 +1,105 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ResourceProviderOperationList"]: + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..db8449803bd --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py @@ -0,0 +1,420 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations: + """SourceControlConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def create_or_update( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + source_control_configuration: "_models.SourceControlConfiguration", + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.SourceControlConfigurationList"]: + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/__init__.py new file mode 100644 index 00000000000..95574a9920b --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/__init__.py @@ -0,0 +1,71 @@ +# 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. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import ComplianceStatus + from ._models_py3 import ErrorDefinition + from ._models_py3 import ErrorResponse + from ._models_py3 import HelmOperatorProperties + from ._models_py3 import ProxyResource + from ._models_py3 import Resource + from ._models_py3 import ResourceProviderOperation + from ._models_py3 import ResourceProviderOperationDisplay + from ._models_py3 import ResourceProviderOperationList + from ._models_py3 import Result + from ._models_py3 import SourceControlConfiguration + from ._models_py3 import SourceControlConfigurationList + from ._models_py3 import SystemData +except (SyntaxError, ImportError): + from ._models import ComplianceStatus # type: ignore + from ._models import ErrorDefinition # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import HelmOperatorProperties # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import Resource # type: ignore + from ._models import ResourceProviderOperation # type: ignore + from ._models import ResourceProviderOperationDisplay # type: ignore + from ._models import ResourceProviderOperationList # type: ignore + from ._models import Result # type: ignore + from ._models import SourceControlConfiguration # type: ignore + from ._models import SourceControlConfigurationList # type: ignore + from ._models import SystemData # type: ignore + +from ._source_control_configuration_client_enums import ( + ComplianceStateType, + CreatedByType, + Enum0, + Enum1, + MessageLevelType, + OperatorScopeType, + OperatorType, + ProvisioningStateType, +) + +__all__ = [ + 'ComplianceStatus', + 'ErrorDefinition', + 'ErrorResponse', + 'HelmOperatorProperties', + 'ProxyResource', + 'Resource', + 'ResourceProviderOperation', + 'ResourceProviderOperationDisplay', + 'ResourceProviderOperationList', + 'Result', + 'SourceControlConfiguration', + 'SourceControlConfigurationList', + 'SystemData', + 'ComplianceStateType', + 'CreatedByType', + 'Enum0', + 'Enum1', + 'MessageLevelType', + 'OperatorScopeType', + 'OperatorType', + 'ProvisioningStateType', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models.py new file mode 100644 index 00000000000..00bd900ea10 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models.py @@ -0,0 +1,495 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = kwargs.get('last_config_applied', None) + self.message = kwargs.get('message', None) + self.message_level = kwargs.get('message_level', None) + + +class ErrorDefinition(msrest.serialization.Model): + """Error definition. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. Service specific error code which serves as the substatus for the HTTP + error code. + :type code: str + :param message: Required. Description of the error. + :type message: str + """ + + _validation = { + 'code': {'required': True}, + 'message': {'required': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorDefinition, self).__init__(**kwargs) + self.code = kwargs['code'] + self.message = kwargs['message'] + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: Error definition. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ErrorDefinition + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = None + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = kwargs.get('chart_version', None) + self.chart_values = kwargs.get('chart_values', None) + + +class Resource(msrest.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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class 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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ResourceProviderOperationDisplay + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.display = kwargs.get('display', None) + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = kwargs.get('provider', None) + self.resource = kwargs.get('resource', None) + self.operation = kwargs.get('operation', None) + self.description = kwargs.get('description', None) + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = None + + +class Result(msrest.serialization.Model): + """Sample result definition. + + :param sample_property: Sample property of type string. + :type sample_property: str + """ + + _attribute_map = { + 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Result, self).__init__(**kwargs) + self.sample_property = kwargs.get('sample_property', None) + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(**kwargs) + self.system_data = None + self.repository_url = kwargs.get('repository_url', None) + self.operator_namespace = kwargs.get('operator_namespace', "default") + self.operator_instance_name = kwargs.get('operator_instance_name', None) + self.operator_type = kwargs.get('operator_type', None) + self.operator_params = kwargs.get('operator_params', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.operator_scope = kwargs.get('operator_scope', "cluster") + self.repository_public_key = None + self.ssh_known_hosts_contents = kwargs.get('ssh_known_hosts_contents', None) + self.enable_helm_operator = kwargs.get('enable_helm_operator', None) + self.helm_operator_properties = kwargs.get('helm_operator_properties', None) + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type 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, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = kwargs.get('created_by', None) + self.created_by_type = kwargs.get('created_by_type', None) + self.created_at = kwargs.get('created_at', None) + self.last_modified_by = kwargs.get('last_modified_by', None) + self.last_modified_by_type = kwargs.get('last_modified_by_type', None) + self.last_modified_at = kwargs.get('last_modified_at', None) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models_py3.py new file mode 100644 index 00000000000..259854d16de --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models_py3.py @@ -0,0 +1,540 @@ +# 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 datetime +from typing import Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._source_control_configuration_client_enums import * + + +class ComplianceStatus(msrest.serialization.Model): + """Compliance Status details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar compliance_state: The compliance state of the configuration. Possible values include: + "Pending", "Compliant", "Noncompliant", "Installed", "Failed". + :vartype compliance_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ComplianceStateType + :param last_config_applied: Datetime the configuration was last applied. + :type last_config_applied: ~datetime.datetime + :param message: Message from when the configuration was applied. + :type message: str + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.MessageLevelType + """ + + _validation = { + 'compliance_state': {'readonly': True}, + } + + _attribute_map = { + 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, + 'message': {'key': 'message', 'type': 'str'}, + 'message_level': {'key': 'messageLevel', 'type': 'str'}, + } + + def __init__( + self, + *, + last_config_applied: Optional[datetime.datetime] = None, + message: Optional[str] = None, + message_level: Optional[Union[str, "MessageLevelType"]] = None, + **kwargs + ): + super(ComplianceStatus, self).__init__(**kwargs) + self.compliance_state = None + self.last_config_applied = last_config_applied + self.message = message + self.message_level = message_level + + +class ErrorDefinition(msrest.serialization.Model): + """Error definition. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. Service specific error code which serves as the substatus for the HTTP + error code. + :type code: str + :param message: Required. Description of the error. + :type message: str + """ + + _validation = { + 'code': {'required': True}, + 'message': {'required': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + *, + code: str, + message: str, + **kwargs + ): + super(ErrorDefinition, self).__init__(**kwargs) + self.code = code + self.message = message + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: Error definition. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ErrorDefinition + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = None + + +class HelmOperatorProperties(msrest.serialization.Model): + """Properties for Helm operator. + + :param chart_version: Version of the operator Helm chart. + :type chart_version: str + :param chart_values: Values override for the operator Helm chart. + :type chart_values: str + """ + + _attribute_map = { + 'chart_version': {'key': 'chartVersion', 'type': 'str'}, + 'chart_values': {'key': 'chartValues', 'type': 'str'}, + } + + def __init__( + self, + *, + chart_version: Optional[str] = None, + chart_values: Optional[str] = None, + **kwargs + ): + super(HelmOperatorProperties, self).__init__(**kwargs) + self.chart_version = chart_version + self.chart_values = chart_values + + +class Resource(msrest.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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class 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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ResourceProviderOperationDisplay + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["ResourceProviderOperationDisplay"] = None, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = name + self.display = display + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _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, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["ResourceProviderOperation"]] = None, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = value + self.next_link = None + + +class Result(msrest.serialization.Model): + """Sample result definition. + + :param sample_property: Sample property of type string. + :type sample_property: str + """ + + _attribute_map = { + 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, + } + + def __init__( + self, + *, + sample_property: Optional[str] = None, + **kwargs + ): + super(Result, self).__init__(**kwargs) + self.sample_property = sample_property + + +class SourceControlConfiguration(ProxyResource): + """The SourceControl Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SystemData + :param repository_url: Url of the SourceControl Repository. + :type repository_url: str + :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type operator_namespace: str + :param operator_instance_name: Instance name of the operator - identifying the specific + configuration. + :type operator_instance_name: str + :param operator_type: Type of the operator. Possible values include: "Flux". + :type operator_type: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.OperatorType + :param operator_params: Any Parameters for the Operator instance in string format. + :type operator_params: str + :param configuration_protected_settings: Name-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :param operator_scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.OperatorScopeType + :ivar repository_public_key: Public Key associated with this SourceControl configuration + (either generated within the cluster or provided by the user). + :vartype repository_public_key: str + :param ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys + required to access private Git instances. + :type ssh_known_hosts_contents: str + :param enable_helm_operator: Option to enable Helm Operator for this git configuration. + :type enable_helm_operator: bool + :param helm_operator_properties: Properties for Helm operator. + :type helm_operator_properties: + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.HelmOperatorProperties + :ivar provisioning_state: The provisioning state of the resource provider. Possible values + include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ProvisioningStateType + :ivar compliance_status: Compliance Status of the Configuration. + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ComplianceStatus + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'compliance_status': {'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'}, + 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, + 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, + 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, + 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, + 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, + 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, + 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, + } + + def __init__( + self, + *, + repository_url: Optional[str] = None, + operator_namespace: Optional[str] = "default", + operator_instance_name: Optional[str] = None, + operator_type: Optional[Union[str, "OperatorType"]] = None, + operator_params: Optional[str] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + operator_scope: Optional[Union[str, "OperatorScopeType"]] = "cluster", + ssh_known_hosts_contents: Optional[str] = None, + enable_helm_operator: Optional[bool] = None, + helm_operator_properties: Optional["HelmOperatorProperties"] = None, + **kwargs + ): + super(SourceControlConfiguration, self).__init__(**kwargs) + self.system_data = None + self.repository_url = repository_url + self.operator_namespace = operator_namespace + self.operator_instance_name = operator_instance_name + self.operator_type = operator_type + self.operator_params = operator_params + self.configuration_protected_settings = configuration_protected_settings + self.operator_scope = operator_scope + self.repository_public_key = None + self.ssh_known_hosts_contents = ssh_known_hosts_contents + self.enable_helm_operator = enable_helm_operator + self.helm_operator_properties = helm_operator_properties + self.provisioning_state = None + self.compliance_status = None + + +class SourceControlConfigurationList(msrest.serialization.Model): + """Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects and a 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 Source Control Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[SourceControlConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SourceControlConfigurationList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type 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, "CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs + ): + super(SystemData, self).__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/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py new file mode 100644 index 00000000000..be122639f51 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py @@ -0,0 +1,87 @@ +# 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, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class ComplianceStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The compliance state of the configuration. + """ + + PENDING = "Pending" + COMPLIANT = "Compliant" + NONCOMPLIANT = "Noncompliant" + INSTALLED = "Installed" + FAILED = "Failed" + +class CreatedByType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The type of identity that created the resource. + """ + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + +class Enum0(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MICROSOFT_CONTAINER_SERVICE = "Microsoft.ContainerService" + MICROSOFT_KUBERNETES = "Microsoft.Kubernetes" + +class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MANAGED_CLUSTERS = "managedClusters" + CONNECTED_CLUSTERS = "connectedClusters" + +class MessageLevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Level of the message. + """ + + ERROR = "Error" + WARNING = "Warning" + INFORMATION = "Information" + +class OperatorScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Scope at which the operator will be installed. + """ + + CLUSTER = "cluster" + NAMESPACE = "namespace" + +class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Type of the operator + """ + + FLUX = "Flux" + +class ProvisioningStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The provisioning state of the resource provider. + """ + + ACCEPTED = "Accepted" + DELETING = "Deleting" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + FAILED = "Failed" diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/__init__.py new file mode 100644 index 00000000000..07db19b318c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations + +__all__ = [ + 'SourceControlConfigurationsOperations', + 'Operations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_operations.py new file mode 100644 index 00000000000..4f46b393205 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_operations.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ResourceProviderOperationList"] + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..7808e3e5917 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py @@ -0,0 +1,429 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations(object): + """SourceControlConfigurationsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def get( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def create_or_update( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + source_control_configuration, # type: "_models.SourceControlConfiguration" + **kwargs # type: Any + ): + # type: (...) -> "_models.SourceControlConfiguration" + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def _delete_initial( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def begin_delete( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + source_control_configuration_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> LROPoller[None] + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.SourceControlConfigurationList"] + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-03-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/__init__.py new file mode 100644 index 00000000000..f13062376d7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/__init__.py @@ -0,0 +1,19 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['SourceControlConfigurationClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_configuration.py new file mode 100644 index 00000000000..65baac1ee82 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_configuration.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-05-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py new file mode 100644 index 00000000000..9b275bd22ad --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py @@ -0,0 +1,124 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import ExtensionsOperations +from .operations import OperationStatusOperations +from .operations import ClusterExtensionTypeOperations +from .operations import ClusterExtensionTypesOperations +from .operations import ExtensionTypeVersionsOperations +from .operations import LocationExtensionTypesOperations +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from . import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar extensions: ExtensionsOperations operations + :vartype extensions: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.ExtensionsOperations + :ivar operation_status: OperationStatusOperations operations + :vartype operation_status: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.OperationStatusOperations + :ivar cluster_extension_type: ClusterExtensionTypeOperations operations + :vartype cluster_extension_type: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.ClusterExtensionTypeOperations + :ivar cluster_extension_types: ClusterExtensionTypesOperations operations + :vartype cluster_extension_types: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.ClusterExtensionTypesOperations + :ivar extension_type_versions: ExtensionTypeVersionsOperations operations + :vartype extension_type_versions: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.ExtensionTypeVersionsOperations + :ivar location_extension_types: LocationExtensionTypesOperations operations + :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.LocationExtensionTypesOperations + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.extensions = ExtensionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operation_status = OperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_type = ClusterExtensionTypeOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_types = ClusterExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.extension_type_versions = ExtensionTypeVersionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_extension_types = LocationExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> SourceControlConfigurationClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_version.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_version.py new file mode 100644 index 00000000000..e5754a47ce6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_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/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/__init__.py new file mode 100644 index 00000000000..ba52c91a7ba --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/__init__.py @@ -0,0 +1,10 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +__all__ = ['SourceControlConfigurationClient'] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_configuration.py new file mode 100644 index 00000000000..1f07c12f646 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-05-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py new file mode 100644 index 00000000000..cf79cd78669 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py @@ -0,0 +1,117 @@ +# 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, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import ExtensionsOperations +from .operations import OperationStatusOperations +from .operations import ClusterExtensionTypeOperations +from .operations import ClusterExtensionTypesOperations +from .operations import ExtensionTypeVersionsOperations +from .operations import LocationExtensionTypesOperations +from .operations import SourceControlConfigurationsOperations +from .operations import Operations +from .. import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar extensions: ExtensionsOperations operations + :vartype extensions: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.ExtensionsOperations + :ivar operation_status: OperationStatusOperations operations + :vartype operation_status: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.OperationStatusOperations + :ivar cluster_extension_type: ClusterExtensionTypeOperations operations + :vartype cluster_extension_type: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.ClusterExtensionTypeOperations + :ivar cluster_extension_types: ClusterExtensionTypesOperations operations + :vartype cluster_extension_types: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.ClusterExtensionTypesOperations + :ivar extension_type_versions: ExtensionTypeVersionsOperations operations + :vartype extension_type_versions: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.ExtensionTypeVersionsOperations + :ivar location_extension_types: LocationExtensionTypesOperations operations + :vartype location_extension_types: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.LocationExtensionTypesOperations + :ivar source_control_configurations: SourceControlConfigurationsOperations operations + :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.SourceControlConfigurationsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.aio.operations.Operations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :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: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.extensions = ExtensionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operation_status = OperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_type = ClusterExtensionTypeOperations( + self._client, self._config, self._serialize, self._deserialize) + self.cluster_extension_types = ClusterExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.extension_type_versions = ExtensionTypeVersionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.location_extension_types = LocationExtensionTypesOperations( + self._client, self._config, self._serialize, self._deserialize) + self.source_control_configurations = SourceControlConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "SourceControlConfigurationClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py similarity index 84% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py index ee01fecd439..5f4504b206d 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/__init__.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py @@ -13,8 +13,6 @@ from ._extension_type_versions_operations import ExtensionTypeVersionsOperations from ._location_extension_types_operations import LocationExtensionTypesOperations from ._source_control_configurations_operations import SourceControlConfigurationsOperations -from ._flux_configurations_operations import FluxConfigurationsOperations -from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations from ._operations import Operations __all__ = [ @@ -25,7 +23,5 @@ 'ExtensionTypeVersionsOperations', 'LocationExtensionTypesOperations', 'SourceControlConfigurationsOperations', - 'FluxConfigurationsOperations', - 'FluxConfigOperationStatusOperations', 'Operations', ] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py similarity index 95% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py index 6f03630d6c4..8253dcae713 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_type_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py @@ -25,7 +25,7 @@ class ClusterExtensionTypeOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -55,17 +55,17 @@ async def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_type: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum5 + :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum5 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_type_name: Extension type name. :type extension_type_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExtensionType, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.ExtensionType + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionType :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionType"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py similarity index 96% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py index 72bc227a473..7ff4216acce 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_cluster_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py @@ -26,7 +26,7 @@ class ClusterExtensionTypesOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -54,12 +54,12 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionTypeList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py index f5e148e4704..bd9f2c220fc 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extension_type_versions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py @@ -26,7 +26,7 @@ class ExtensionTypeVersionsOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -55,7 +55,7 @@ def list( :type extension_type_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionVersionList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionList] + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionVersionList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionVersionList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py index 16aa34e0fd6..a3145bf7f8f 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_extensions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py @@ -28,7 +28,7 @@ class ExtensionsOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -123,16 +123,16 @@ async def begin_create( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. :type extension_name: str :param extension: Properties necessary to Create an Extension. - :type extension: ~azure.mgmt.kubernetesconfiguration.models.Extension + :type extension: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. @@ -140,7 +140,7 @@ async def begin_create( :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Extension or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.kubernetesconfiguration.models.Extension] + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] @@ -210,17 +210,17 @@ async def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. :type extension_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Extension, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.Extension + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] @@ -339,10 +339,10 @@ async def begin_delete( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. @@ -423,15 +423,15 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionsList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionsList] + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionsList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionsList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py index f9a252028e5..f435cdfdcb5 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_location_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py @@ -26,7 +26,7 @@ class LocationExtensionTypesOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -52,7 +52,7 @@ def list( :type location: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionTypeList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py similarity index 95% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py index a8f41c82fe9..4019731f059 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operation_status_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py @@ -26,7 +26,7 @@ class OperationStatusOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -57,10 +57,10 @@ async def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. @@ -69,7 +69,7 @@ async def get( :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatusResult, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperationStatusResult :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] @@ -132,15 +132,15 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationStatusList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.OperationStatusList] + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperationStatusList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusList"] @@ -148,7 +148,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py new file mode 100644 index 00000000000..3c82397333f --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py @@ -0,0 +1,105 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ResourceProviderOperationList"]: + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py new file mode 100644 index 00000000000..b6aaf25443d --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py @@ -0,0 +1,420 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class SourceControlConfigurationsOperations: + """SourceControlConfigurationsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def get( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Gets details of the Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def create_or_update( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + source_control_configuration: "_models.SourceControlConfiguration", + **kwargs: Any + ) -> "_models.SourceControlConfiguration": + """Create a new Kubernetes Source Control Configuration. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration + :keyword callable cls: A custom type or function that will be passed the direct response + :return: SourceControlConfiguration, or the result of cls(response) + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + content_type = kwargs.pop("content_type", "application/json") + accept = "application/json" + + # Construct URL + url = self.create_or_update.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def _delete_initial( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> None: + cls = kwargs.pop('cls', None) # type: ClsType[None] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = self._delete_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + async def begin_delete( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + source_control_configuration_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """This will delete the YAML file used to set up the Source control configuration, thus stopping + future sync from the source repo. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :param source_control_configuration_name: Name of the Source Control Configuration. + :type source_control_configuration_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. + Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType[None] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + cluster_rp=cluster_rp, + cluster_resource_name=cluster_resource_name, + cluster_name=cluster_name, + source_control_configuration_name=source_control_configuration_name, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + if cls: + return cls(pipeline_response, None, {}) + + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str'), + } + + if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} # type: ignore + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.SourceControlConfigurationList"]: + """List all Source Control Configurations. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfigurationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('SourceControlConfigurationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/__init__.py similarity index 84% rename from src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/__init__.py index 1c05522a343..e97bdb99166 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/models/__init__.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/__init__.py @@ -19,16 +19,11 @@ from ._models_py3 import ExtensionVersionList from ._models_py3 import ExtensionVersionListVersionsItem from ._models_py3 import ExtensionsList - from ._models_py3 import FluxConfiguration - from ._models_py3 import FluxConfigurationsList - from ._models_py3 import GitRepositoryDefinition from ._models_py3 import HelmOperatorProperties from ._models_py3 import Identity - from ._models_py3 import KustomizationDefinition from ._models_py3 import OperationStatusList from ._models_py3 import OperationStatusResult from ._models_py3 import ProxyResource - from ._models_py3 import RepositoryRefDefinition from ._models_py3 import Resource from ._models_py3 import ResourceProviderOperation from ._models_py3 import ResourceProviderOperationDisplay @@ -53,16 +48,11 @@ from ._models import ExtensionVersionList # type: ignore from ._models import ExtensionVersionListVersionsItem # type: ignore from ._models import ExtensionsList # type: ignore - from ._models import FluxConfiguration # type: ignore - from ._models import FluxConfigurationsList # type: ignore - from ._models import GitRepositoryDefinition # type: ignore from ._models import HelmOperatorProperties # type: ignore from ._models import Identity # type: ignore - from ._models import KustomizationDefinition # type: ignore from ._models import OperationStatusList # type: ignore from ._models import OperationStatusResult # type: ignore from ._models import ProxyResource # type: ignore - from ._models import RepositoryRefDefinition # type: ignore from ._models import Resource # type: ignore from ._models import ResourceProviderOperation # type: ignore from ._models import ResourceProviderOperationDisplay # type: ignore @@ -82,16 +72,12 @@ Enum0, Enum1, Enum5, - KustomizationValidationType, LevelType, MessageLevelType, OperatorScopeType, OperatorType, ProvisioningState, ProvisioningStateType, - ScopeType, - SourceKindType, - SyncStateType, ) __all__ = [ @@ -107,16 +93,11 @@ 'ExtensionVersionList', 'ExtensionVersionListVersionsItem', 'ExtensionsList', - 'FluxConfiguration', - 'FluxConfigurationsList', - 'GitRepositoryDefinition', 'HelmOperatorProperties', 'Identity', - 'KustomizationDefinition', 'OperationStatusList', 'OperationStatusResult', 'ProxyResource', - 'RepositoryRefDefinition', 'Resource', 'ResourceProviderOperation', 'ResourceProviderOperationDisplay', @@ -134,14 +115,10 @@ 'Enum0', 'Enum1', 'Enum5', - 'KustomizationValidationType', 'LevelType', 'MessageLevelType', 'OperatorScopeType', 'OperatorType', 'ProvisioningState', 'ProvisioningStateType', - 'ScopeType', - 'SourceKindType', - 'SyncStateType', ] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py similarity index 69% rename from src/k8s-config/azext_k8s_config/vendored_sdks/models/_models.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py index cb9cf66312e..2ad2439168e 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py @@ -131,14 +131,15 @@ class ComplianceStatus(msrest.serialization.Model): :ivar compliance_state: The compliance state of the configuration. Possible values include: "Pending", "Compliant", "Noncompliant", "Installed", "Failed". :vartype compliance_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ComplianceStateType + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ComplianceStateType :param last_config_applied: Datetime the configuration was last applied. :type last_config_applied: ~datetime.datetime :param message: Message from when the configuration was applied. :type message: str :param message_level: Level of the message. Possible values include: "Error", "Warning", "Information". - :type message_level: str or ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.MessageLevelType """ _validation = { @@ -205,9 +206,11 @@ class ErrorDetail(msrest.serialization.Model): :ivar target: The error target. :vartype target: str :ivar details: The error details. - :vartype details: list[~azure.mgmt.kubernetesconfiguration.models.ErrorDetail] + :vartype details: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail] :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.kubernetesconfiguration.models.ErrorAdditionalInfo] + :vartype additional_info: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorAdditionalInfo] """ _validation = { @@ -242,7 +245,7 @@ class ErrorResponse(msrest.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.). :param error: The error object. - :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :type error: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail """ _attribute_map = { @@ -271,10 +274,10 @@ class Extension(ProxyResource): "Microsoft.Storage/storageAccounts". :vartype type: str :param identity: Identity of the Extension resource. - :type identity: ~azure.mgmt.kubernetesconfiguration.models.Identity + :type identity: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Identity :ivar system_data: Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData :param extension_type: Type of the Extension, of which this resource is an instance of. It must be one of the Extension Types registered with Microsoft.KubernetesConfiguration by the Extension publisher. @@ -289,7 +292,7 @@ class Extension(ProxyResource): version. autoUpgradeMinorVersion must be 'false'. :type version: str :param scope: Scope at which the extension is installed. - :type scope: ~azure.mgmt.kubernetesconfiguration.models.Scope + :type scope: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Scope :param configuration_settings: Configuration settings, as name-value pairs for configuring this extension. :type configuration_settings: dict[str, str] @@ -299,11 +302,12 @@ class Extension(ProxyResource): :ivar provisioning_state: Status of installation of this extension. Possible values include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ProvisioningState :param statuses: Status from this extension. - :type statuses: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionStatus] + :type statuses: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionStatus] :ivar error_info: Error information from the Agent - e.g. errors during installation. - :vartype error_info: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :vartype error_info: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail :ivar custom_location_settings: Custom Location settings properties. :vartype custom_location_settings: dict[str, str] :ivar package_uri: Uri of the Helm package. @@ -368,7 +372,7 @@ class ExtensionsList(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of Extensions within a Kubernetes cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.Extension] + :vartype value: list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension] :ivar next_link: URL to get the next set of extension objects, if any. :vartype next_link: str """ @@ -401,7 +405,7 @@ class ExtensionStatus(msrest.serialization.Model): :type display_status: str :param level: Level of the status. Possible values include: "Error", "Warning", "Information". Default value: "Information". - :type level: str or ~azure.mgmt.kubernetesconfiguration.models.LevelType + :type level: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.LevelType :param message: Detailed message of the status from the Extension. :type message: str :param time: DateLiteral (per ISO8601) noting the time of installation status. @@ -434,14 +438,16 @@ class ExtensionType(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar system_data: Metadata pertaining to creation and last modification of the resource. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData :ivar release_trains: Extension release train: preview or stable. :vartype release_trains: list[str] :ivar cluster_types: Cluster types. Possible values include: "connectedClusters", "managedClusters". - :vartype cluster_types: str or ~azure.mgmt.kubernetesconfiguration.models.ClusterTypes + :vartype cluster_types: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ClusterTypes :ivar supported_scopes: Extension scopes. - :vartype supported_scopes: ~azure.mgmt.kubernetesconfiguration.models.SupportedScopes + :vartype supported_scopes: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SupportedScopes """ _validation = { @@ -473,7 +479,7 @@ class ExtensionTypeList(msrest.serialization.Model): """List Extension Types. :param value: The list of Extension Types. - :type value: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionType] + :type value: list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionType] :param next_link: The link to fetch the next page of Extension Types. :type next_link: str """ @@ -499,11 +505,11 @@ class ExtensionVersionList(msrest.serialization.Model): :param versions: Versions available for this Extension Type. :type versions: - list[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionListVersionsItem] + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionVersionListVersionsItem] :param next_link: The link to fetch the next page of Extension Types. :type next_link: str :ivar system_data: Metadata pertaining to creation and last modification of the resource. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData """ _validation = { @@ -549,204 +555,6 @@ def __init__( self.versions = kwargs.get('versions', None) -class FluxConfiguration(ProxyResource): - """The Flux Configuration object returned in Get & Put response. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :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: Top level metadata - https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData - :param scope: Scope at which the operator will be installed. Possible values include: - "cluster", "namespace". Default value: "cluster". - :type scope: str or ~azure.mgmt.kubernetesconfiguration.models.ScopeType - :param namespace: The namespace to which this configuration is installed to. Maximum of 253 - lower case alphanumeric characters, hyphen and period only. - :type namespace: str - :param source_kind: Source Kind to pull the configuration data from. Possible values include: - "GitRepository". - :type source_kind: str or ~azure.mgmt.kubernetesconfiguration.models.SourceKindType - :param suspend: Whether this configuration should suspend its reconciliation of its - kustomizations and sources. - :type suspend: bool - :param git_repository: Parameters to reconcile to the GitRepository source kind type. - :type git_repository: ~azure.mgmt.kubernetesconfiguration.models.GitRepositoryDefinition - :param kustomizations: Array of kustomizations used to reconcile the artifact pulled by the - source type on the cluster. - :type kustomizations: list[~azure.mgmt.kubernetesconfiguration.models.KustomizationDefinition] - :param configuration_protected_settings: Key-value pairs of protected configuration settings - for the configuration. - :type configuration_protected_settings: dict[str, str] - :ivar statuses: Statuses of the Flux Kubernetes resources created by the fluxConfiguration or - created by the managed objects provisioned by the fluxConfiguration. - :vartype statuses: list[dict[str, any]] - :ivar repository_public_key: Public Key associated with this fluxConfiguration (either - generated within the cluster or provided by the user). - :vartype repository_public_key: str - :ivar last_synced_time: Datetime the fluxConfiguration has been synced with the Azure control - plane. - :vartype last_synced_time: str - :ivar last_synced_commit: Branch and SHA of the last source commit synced with the cluster. - :vartype last_synced_commit: str - :ivar last_config_applied_time: Datetime the fluxConfiguration was last applied. - :vartype last_config_applied_time: str - :ivar sync_state: Combined status of the Flux Kubernetes resources created by the - fluxConfiguration or created by the managed objects. Possible values include: "compliant", - "non-compliant", "syncing". Default value: "syncing". - :vartype sync_state: str or ~azure.mgmt.kubernetesconfiguration.models.SyncStateType - :ivar provisioning_state: Status of the creation of the fluxConfiguration. Possible values - include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". - :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState - :ivar message: Error message returned to the user in the case of provisioning failure. - :vartype message: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'statuses': {'readonly': True}, - 'repository_public_key': {'readonly': True}, - 'last_synced_time': {'readonly': True}, - 'last_synced_commit': {'readonly': True}, - 'last_config_applied_time': {'readonly': True}, - 'sync_state': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'message': {'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'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'namespace': {'key': 'properties.namespace', 'type': 'str'}, - 'source_kind': {'key': 'properties.sourceKind', 'type': 'str'}, - 'suspend': {'key': 'properties.suspend', 'type': 'bool'}, - 'git_repository': {'key': 'properties.gitRepository', 'type': 'GitRepositoryDefinition'}, - 'kustomizations': {'key': 'properties.kustomizations', 'type': '[KustomizationDefinition]'}, - 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, - 'statuses': {'key': 'properties.statuses', 'type': '[{object}]'}, - 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, - 'last_synced_time': {'key': 'properties.lastSyncedTime', 'type': 'str'}, - 'last_synced_commit': {'key': 'properties.lastSyncedCommit', 'type': 'str'}, - 'last_config_applied_time': {'key': 'properties.lastConfigAppliedTime', 'type': 'str'}, - 'sync_state': {'key': 'properties.syncState', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'message': {'key': 'properties.message', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(FluxConfiguration, self).__init__(**kwargs) - self.system_data = None - self.scope = kwargs.get('scope', "cluster") - self.namespace = kwargs.get('namespace', "default") - self.source_kind = kwargs.get('source_kind', None) - self.suspend = kwargs.get('suspend', False) - self.git_repository = kwargs.get('git_repository', None) - self.kustomizations = kwargs.get('kustomizations', None) - self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) - self.statuses = None - self.repository_public_key = None - self.last_synced_time = None - self.last_synced_commit = None - self.last_config_applied_time = None - self.sync_state = None - self.provisioning_state = None - self.message = None - - -class FluxConfigurationsList(msrest.serialization.Model): - """Result of the request to list Flux Configurations. It contains a list of FluxConfiguration objects and a 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 Flux Configurations within a Kubernetes cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] - :ivar next_link: URL to get the next set of configuration objects, if any. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[FluxConfiguration]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(FluxConfigurationsList, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class GitRepositoryDefinition(msrest.serialization.Model): - """Parameters to reconcile to the GitRepository source kind type. - - :param url: The URL to sync for the flux configuration git repository. - :type url: str - :param timeout: The maximum time to attempt to reconcile the cluster git repository source with - the remote. - :type timeout: str - :param sync_interval: The interval at which to re-reconcile the cluster git repository source - with the remote. - :type sync_interval: str - :param repository_ref: The source reference for the GitRepository object. - :type repository_ref: ~azure.mgmt.kubernetesconfiguration.models.RepositoryRefDefinition - :param ssh_known_hosts: Base64-encoded known_hosts value containing public SSH keys required to - access private git repositories over SSH. - :type ssh_known_hosts: str - :param https_user: HTTPS username used to access private git repositories over HTTPS. - :type https_user: str - :param auth_ref_override: Name of a local secret on the Kubernetes cluster to use as the - authentication secret rather than the managed or user-provided configuration secrets. - :type auth_ref_override: str - """ - - _attribute_map = { - 'url': {'key': 'url', 'type': 'str'}, - 'timeout': {'key': 'timeout', 'type': 'str'}, - 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, - 'repository_ref': {'key': 'repositoryRef', 'type': 'RepositoryRefDefinition'}, - 'ssh_known_hosts': {'key': 'sshKnownHosts', 'type': 'str'}, - 'https_user': {'key': 'httpsUser', 'type': 'str'}, - 'auth_ref_override': {'key': 'authRefOverride', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(GitRepositoryDefinition, self).__init__(**kwargs) - self.url = kwargs.get('url', None) - self.timeout = kwargs.get('timeout', None) - self.sync_interval = kwargs.get('sync_interval', None) - self.repository_ref = kwargs.get('repository_ref', None) - self.ssh_known_hosts = kwargs.get('ssh_known_hosts', None) - self.https_user = kwargs.get('https_user', None) - self.auth_ref_override = kwargs.get('auth_ref_override', None) - - class HelmOperatorProperties(msrest.serialization.Model): """Properties for Helm operator. @@ -806,70 +614,14 @@ def __init__( self.tenant_id = None -class KustomizationDefinition(msrest.serialization.Model): - """KustomizationDefinition. - - :param name: The name of the Kustomization object to create on the cluster. - :type name: str - :param path: The path in the source reference to reconcile on the cluster. - :type path: str - :param depends_on: Specifies other Kustomizations that this Kustomization depends on. This - Kustomization will not reconcile until all dependencies have completed their reconciliation. - :type depends_on: list[str] - :param timeout: The maximum time to attempt to reconcile the Kustomization on the cluster. - :type timeout: str - :param sync_interval: The interval at which to re-reconcile the Kustomization on the cluster. - :type sync_interval: str - :param retry_interval: The interval at which to re-reconcile the Kustomization on the cluster - in the event of failure on reconciliation. - :type retry_interval: str - :param prune: Enable/disable garbage collections of Kubernetes objects created by this - Kustomization. - :type prune: bool - :param validation: Specify whether to validate the Kubernetes objects referenced in the - Kustomization before applying them to the cluster. Possible values include: "none", "client", - "server". Default value: "none". - :type validation: str or ~azure.mgmt.kubernetesconfiguration.models.KustomizationValidationType - :param force: Enable/disable re-creating Kubernetes resources on the cluster when patching - fails due to an immutable field change. - :type force: bool - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'path': {'key': 'path', 'type': 'str'}, - 'depends_on': {'key': 'dependsOn', 'type': '[str]'}, - 'timeout': {'key': 'timeout', 'type': 'str'}, - 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, - 'retry_interval': {'key': 'retryInterval', 'type': 'str'}, - 'prune': {'key': 'prune', 'type': 'bool'}, - 'validation': {'key': 'validation', 'type': 'str'}, - 'force': {'key': 'force', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(KustomizationDefinition, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.path = kwargs.get('path', "") - self.depends_on = kwargs.get('depends_on', None) - self.timeout = kwargs.get('timeout', None) - self.sync_interval = kwargs.get('sync_interval', None) - self.retry_interval = kwargs.get('retry_interval', None) - self.prune = kwargs.get('prune', None) - self.validation = kwargs.get('validation', "none") - self.force = kwargs.get('force', None) - - class OperationStatusList(msrest.serialization.Model): """The async operations in progress, in the cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of async operations in progress, in the cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult] + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperationStatusResult] :ivar next_link: URL to get the next set of Operation Result objects, if any. :vartype next_link: str """ @@ -909,7 +661,7 @@ class OperationStatusResult(msrest.serialization.Model): :param properties: Additional information, if available. :type properties: dict[str, str] :ivar error: If present, details of the operation error. - :vartype error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail """ _validation = { @@ -937,39 +689,6 @@ def __init__( self.error = None -class RepositoryRefDefinition(msrest.serialization.Model): - """The source reference for the GitRepository object. - - :param branch: The git repository branch name to checkout. - :type branch: str - :param tag: The git repository tag name to checkout. This takes precedence over branch. - :type tag: str - :param semver: The semver range used to match against git repository tags. This takes - precedence over tag. - :type semver: str - :param commit: The commit SHA to checkout. This value must be combined with the branch name to - be valid. This takes precedence over semver. - :type commit: str - """ - - _attribute_map = { - 'branch': {'key': 'branch', 'type': 'str'}, - 'tag': {'key': 'tag', 'type': 'str'}, - 'semver': {'key': 'semver', 'type': 'str'}, - 'commit': {'key': 'commit', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RepositoryRefDefinition, self).__init__(**kwargs) - self.branch = kwargs.get('branch', None) - self.tag = kwargs.get('tag', None) - self.semver = kwargs.get('semver', None) - self.commit = kwargs.get('commit', None) - - class ResourceProviderOperation(msrest.serialization.Model): """Supported operation of this resource provider. @@ -978,7 +697,8 @@ class ResourceProviderOperation(msrest.serialization.Model): :param name: Operation name, in format of {provider}/{resource}/{operation}. :type name: str :param display: Display metadata associated with the operation. - :type display: ~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationDisplay + :type display: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ResourceProviderOperationDisplay :param origin: The intended executor of the operation;governs the display of the operation in the RBAC UX and the audit logs UX. :type origin: str @@ -1045,7 +765,8 @@ class ResourceProviderOperationList(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :param value: List of operations supported by this resource provider. - :type value: list[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperation] + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ResourceProviderOperation] :ivar next_link: URL to the next set of results, if any. :vartype next_link: str """ @@ -1072,9 +793,9 @@ class Scope(msrest.serialization.Model): """Scope of the extension. It can be either Cluster or Namespace; but not both. :param cluster: Specifies that the scope of the extension is Cluster. - :type cluster: ~azure.mgmt.kubernetesconfiguration.models.ScopeCluster + :type cluster: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ScopeCluster :param namespace: Specifies that the scope of the extension is Namespace. - :type namespace: ~azure.mgmt.kubernetesconfiguration.models.ScopeNamespace + :type namespace: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ScopeNamespace """ _attribute_map = { @@ -1146,7 +867,7 @@ class SourceControlConfiguration(ProxyResource): :vartype type: str :ivar system_data: Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData :param repository_url: Url of the SourceControl Repository. :type repository_url: str :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 @@ -1156,7 +877,8 @@ class SourceControlConfiguration(ProxyResource): configuration. :type operator_instance_name: str :param operator_type: Type of the operator. Possible values include: "Flux". - :type operator_type: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorType + :type operator_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperatorType :param operator_params: Any Parameters for the Operator instance in string format. :type operator_params: str :param configuration_protected_settings: Name-value pairs of protected configuration settings @@ -1164,7 +886,8 @@ class SourceControlConfiguration(ProxyResource): :type configuration_protected_settings: dict[str, str] :param operator_scope: Scope at which the operator will be installed. Possible values include: "cluster", "namespace". Default value: "cluster". - :type operator_scope: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorScopeType + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperatorScopeType :ivar repository_public_key: Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). :vartype repository_public_key: str @@ -1175,13 +898,14 @@ class SourceControlConfiguration(ProxyResource): :type enable_helm_operator: bool :param helm_operator_properties: Properties for Helm operator. :type helm_operator_properties: - ~azure.mgmt.kubernetesconfiguration.models.HelmOperatorProperties + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.HelmOperatorProperties :ivar provisioning_state: The provisioning state of the resource provider. Possible values include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningStateType + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ProvisioningStateType :ivar compliance_status: Compliance Status of the Configuration. - :vartype compliance_status: ~azure.mgmt.kubernetesconfiguration.models.ComplianceStatus + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ComplianceStatus """ _validation = { @@ -1241,7 +965,8 @@ class SourceControlConfigurationList(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of Source Control Configurations within a Kubernetes cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration] + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration] :ivar next_link: URL to get the next set of configuration objects, if any. :vartype next_link: str """ @@ -1271,7 +996,8 @@ class SupportedScopes(msrest.serialization.Model): :param default_scope: Default extension scopes: cluster or namespace. :type default_scope: str :param cluster_scope_settings: Scope settings. - :type cluster_scope_settings: ~azure.mgmt.kubernetesconfiguration.models.ClusterScopeSettings + :type cluster_scope_settings: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ClusterScopeSettings """ _attribute_map = { @@ -1295,14 +1021,16 @@ class SystemData(msrest.serialization.Model): :type created_by: str :param created_by_type: The type of identity that created the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". - :type created_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :type created_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.CreatedByType :param created_at: The timestamp of resource creation (UTC). :type created_at: ~datetime.datetime :param last_modified_by: The identity that last modified the resource. :type last_modified_by: str :param last_modified_by_type: The type of identity that last modified the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". - :type last_modified_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :type last_modified_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.CreatedByType :param last_modified_at: The timestamp of resource last modification (UTC). :type last_modified_at: ~datetime.datetime """ diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py similarity index 69% rename from src/k8s-config/azext_k8s_config/vendored_sdks/models/_models_py3.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py index 23a4494072e..ffc3547f685 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_models_py3.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py @@ -139,14 +139,15 @@ class ComplianceStatus(msrest.serialization.Model): :ivar compliance_state: The compliance state of the configuration. Possible values include: "Pending", "Compliant", "Noncompliant", "Installed", "Failed". :vartype compliance_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ComplianceStateType + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ComplianceStateType :param last_config_applied: Datetime the configuration was last applied. :type last_config_applied: ~datetime.datetime :param message: Message from when the configuration was applied. :type message: str :param message_level: Level of the message. Possible values include: "Error", "Warning", "Information". - :type message_level: str or ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType + :type message_level: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.MessageLevelType """ _validation = { @@ -217,9 +218,11 @@ class ErrorDetail(msrest.serialization.Model): :ivar target: The error target. :vartype target: str :ivar details: The error details. - :vartype details: list[~azure.mgmt.kubernetesconfiguration.models.ErrorDetail] + :vartype details: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail] :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.kubernetesconfiguration.models.ErrorAdditionalInfo] + :vartype additional_info: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorAdditionalInfo] """ _validation = { @@ -254,7 +257,7 @@ class ErrorResponse(msrest.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.). :param error: The error object. - :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :type error: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail """ _attribute_map = { @@ -285,10 +288,10 @@ class Extension(ProxyResource): "Microsoft.Storage/storageAccounts". :vartype type: str :param identity: Identity of the Extension resource. - :type identity: ~azure.mgmt.kubernetesconfiguration.models.Identity + :type identity: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Identity :ivar system_data: Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData :param extension_type: Type of the Extension, of which this resource is an instance of. It must be one of the Extension Types registered with Microsoft.KubernetesConfiguration by the Extension publisher. @@ -303,7 +306,7 @@ class Extension(ProxyResource): version. autoUpgradeMinorVersion must be 'false'. :type version: str :param scope: Scope at which the extension is installed. - :type scope: ~azure.mgmt.kubernetesconfiguration.models.Scope + :type scope: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Scope :param configuration_settings: Configuration settings, as name-value pairs for configuring this extension. :type configuration_settings: dict[str, str] @@ -313,11 +316,12 @@ class Extension(ProxyResource): :ivar provisioning_state: Status of installation of this extension. Possible values include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ProvisioningState :param statuses: Status from this extension. - :type statuses: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionStatus] + :type statuses: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionStatus] :ivar error_info: Error information from the Agent - e.g. errors during installation. - :vartype error_info: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :vartype error_info: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail :ivar custom_location_settings: Custom Location settings properties. :vartype custom_location_settings: dict[str, str] :ivar package_uri: Uri of the Helm package. @@ -392,7 +396,7 @@ class ExtensionsList(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of Extensions within a Kubernetes cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.Extension] + :vartype value: list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension] :ivar next_link: URL to get the next set of extension objects, if any. :vartype next_link: str """ @@ -425,7 +429,7 @@ class ExtensionStatus(msrest.serialization.Model): :type display_status: str :param level: Level of the status. Possible values include: "Error", "Warning", "Information". Default value: "Information". - :type level: str or ~azure.mgmt.kubernetesconfiguration.models.LevelType + :type level: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.LevelType :param message: Detailed message of the status from the Extension. :type message: str :param time: DateLiteral (per ISO8601) noting the time of installation status. @@ -464,14 +468,16 @@ class ExtensionType(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar system_data: Metadata pertaining to creation and last modification of the resource. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData :ivar release_trains: Extension release train: preview or stable. :vartype release_trains: list[str] :ivar cluster_types: Cluster types. Possible values include: "connectedClusters", "managedClusters". - :vartype cluster_types: str or ~azure.mgmt.kubernetesconfiguration.models.ClusterTypes + :vartype cluster_types: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ClusterTypes :ivar supported_scopes: Extension scopes. - :vartype supported_scopes: ~azure.mgmt.kubernetesconfiguration.models.SupportedScopes + :vartype supported_scopes: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SupportedScopes """ _validation = { @@ -503,7 +509,7 @@ class ExtensionTypeList(msrest.serialization.Model): """List Extension Types. :param value: The list of Extension Types. - :type value: list[~azure.mgmt.kubernetesconfiguration.models.ExtensionType] + :type value: list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionType] :param next_link: The link to fetch the next page of Extension Types. :type next_link: str """ @@ -532,11 +538,11 @@ class ExtensionVersionList(msrest.serialization.Model): :param versions: Versions available for this Extension Type. :type versions: - list[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionListVersionsItem] + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionVersionListVersionsItem] :param next_link: The link to fetch the next page of Extension Types. :type next_link: str :ivar system_data: Metadata pertaining to creation and last modification of the resource. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData """ _validation = { @@ -588,220 +594,6 @@ def __init__( self.versions = versions -class FluxConfiguration(ProxyResource): - """The Flux Configuration object returned in Get & Put response. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :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: Top level metadata - https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData - :param scope: Scope at which the operator will be installed. Possible values include: - "cluster", "namespace". Default value: "cluster". - :type scope: str or ~azure.mgmt.kubernetesconfiguration.models.ScopeType - :param namespace: The namespace to which this configuration is installed to. Maximum of 253 - lower case alphanumeric characters, hyphen and period only. - :type namespace: str - :param source_kind: Source Kind to pull the configuration data from. Possible values include: - "GitRepository". - :type source_kind: str or ~azure.mgmt.kubernetesconfiguration.models.SourceKindType - :param suspend: Whether this configuration should suspend its reconciliation of its - kustomizations and sources. - :type suspend: bool - :param git_repository: Parameters to reconcile to the GitRepository source kind type. - :type git_repository: ~azure.mgmt.kubernetesconfiguration.models.GitRepositoryDefinition - :param kustomizations: Array of kustomizations used to reconcile the artifact pulled by the - source type on the cluster. - :type kustomizations: list[~azure.mgmt.kubernetesconfiguration.models.KustomizationDefinition] - :param configuration_protected_settings: Key-value pairs of protected configuration settings - for the configuration. - :type configuration_protected_settings: dict[str, str] - :ivar statuses: Statuses of the Flux Kubernetes resources created by the fluxConfiguration or - created by the managed objects provisioned by the fluxConfiguration. - :vartype statuses: list[dict[str, any]] - :ivar repository_public_key: Public Key associated with this fluxConfiguration (either - generated within the cluster or provided by the user). - :vartype repository_public_key: str - :ivar last_synced_time: Datetime the fluxConfiguration has been synced with the Azure control - plane. - :vartype last_synced_time: str - :ivar last_synced_commit: Branch and SHA of the last source commit synced with the cluster. - :vartype last_synced_commit: str - :ivar last_config_applied_time: Datetime the fluxConfiguration was last applied. - :vartype last_config_applied_time: str - :ivar sync_state: Combined status of the Flux Kubernetes resources created by the - fluxConfiguration or created by the managed objects. Possible values include: "compliant", - "non-compliant", "syncing". Default value: "syncing". - :vartype sync_state: str or ~azure.mgmt.kubernetesconfiguration.models.SyncStateType - :ivar provisioning_state: Status of the creation of the fluxConfiguration. Possible values - include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". - :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningState - :ivar message: Error message returned to the user in the case of provisioning failure. - :vartype message: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'statuses': {'readonly': True}, - 'repository_public_key': {'readonly': True}, - 'last_synced_time': {'readonly': True}, - 'last_synced_commit': {'readonly': True}, - 'last_config_applied_time': {'readonly': True}, - 'sync_state': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'message': {'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'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'namespace': {'key': 'properties.namespace', 'type': 'str'}, - 'source_kind': {'key': 'properties.sourceKind', 'type': 'str'}, - 'suspend': {'key': 'properties.suspend', 'type': 'bool'}, - 'git_repository': {'key': 'properties.gitRepository', 'type': 'GitRepositoryDefinition'}, - 'kustomizations': {'key': 'properties.kustomizations', 'type': '[KustomizationDefinition]'}, - 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, - 'statuses': {'key': 'properties.statuses', 'type': '[{object}]'}, - 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, - 'last_synced_time': {'key': 'properties.lastSyncedTime', 'type': 'str'}, - 'last_synced_commit': {'key': 'properties.lastSyncedCommit', 'type': 'str'}, - 'last_config_applied_time': {'key': 'properties.lastConfigAppliedTime', 'type': 'str'}, - 'sync_state': {'key': 'properties.syncState', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'message': {'key': 'properties.message', 'type': 'str'}, - } - - def __init__( - self, - *, - scope: Optional[Union[str, "ScopeType"]] = "cluster", - namespace: Optional[str] = "default", - source_kind: Optional[Union[str, "SourceKindType"]] = None, - suspend: Optional[bool] = False, - git_repository: Optional["GitRepositoryDefinition"] = None, - kustomizations: Optional[List["KustomizationDefinition"]] = None, - configuration_protected_settings: Optional[Dict[str, str]] = None, - **kwargs - ): - super(FluxConfiguration, self).__init__(**kwargs) - self.system_data = None - self.scope = scope - self.namespace = namespace - self.source_kind = source_kind - self.suspend = suspend - self.git_repository = git_repository - self.kustomizations = kustomizations - self.configuration_protected_settings = configuration_protected_settings - self.statuses = None - self.repository_public_key = None - self.last_synced_time = None - self.last_synced_commit = None - self.last_config_applied_time = None - self.sync_state = None - self.provisioning_state = None - self.message = None - - -class FluxConfigurationsList(msrest.serialization.Model): - """Result of the request to list Flux Configurations. It contains a list of FluxConfiguration objects and a 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 Flux Configurations within a Kubernetes cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] - :ivar next_link: URL to get the next set of configuration objects, if any. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[FluxConfiguration]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(FluxConfigurationsList, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class GitRepositoryDefinition(msrest.serialization.Model): - """Parameters to reconcile to the GitRepository source kind type. - - :param url: The URL to sync for the flux configuration git repository. - :type url: str - :param timeout: The maximum time to attempt to reconcile the cluster git repository source with - the remote. - :type timeout: str - :param sync_interval: The interval at which to re-reconcile the cluster git repository source - with the remote. - :type sync_interval: str - :param repository_ref: The source reference for the GitRepository object. - :type repository_ref: ~azure.mgmt.kubernetesconfiguration.models.RepositoryRefDefinition - :param ssh_known_hosts: Base64-encoded known_hosts value containing public SSH keys required to - access private git repositories over SSH. - :type ssh_known_hosts: str - :param https_user: HTTPS username used to access private git repositories over HTTPS. - :type https_user: str - :param auth_ref_override: Name of a local secret on the Kubernetes cluster to use as the - authentication secret rather than the managed or user-provided configuration secrets. - :type auth_ref_override: str - """ - - _attribute_map = { - 'url': {'key': 'url', 'type': 'str'}, - 'timeout': {'key': 'timeout', 'type': 'str'}, - 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, - 'repository_ref': {'key': 'repositoryRef', 'type': 'RepositoryRefDefinition'}, - 'ssh_known_hosts': {'key': 'sshKnownHosts', 'type': 'str'}, - 'https_user': {'key': 'httpsUser', 'type': 'str'}, - 'auth_ref_override': {'key': 'authRefOverride', 'type': 'str'}, - } - - def __init__( - self, - *, - url: Optional[str] = None, - timeout: Optional[str] = None, - sync_interval: Optional[str] = None, - repository_ref: Optional["RepositoryRefDefinition"] = None, - ssh_known_hosts: Optional[str] = None, - https_user: Optional[str] = None, - auth_ref_override: Optional[str] = None, - **kwargs - ): - super(GitRepositoryDefinition, self).__init__(**kwargs) - self.url = url - self.timeout = timeout - self.sync_interval = sync_interval - self.repository_ref = repository_ref - self.ssh_known_hosts = ssh_known_hosts - self.https_user = https_user - self.auth_ref_override = auth_ref_override - - class HelmOperatorProperties(msrest.serialization.Model): """Properties for Helm operator. @@ -864,80 +656,14 @@ def __init__( self.tenant_id = None -class KustomizationDefinition(msrest.serialization.Model): - """KustomizationDefinition. - - :param name: The name of the Kustomization object to create on the cluster. - :type name: str - :param path: The path in the source reference to reconcile on the cluster. - :type path: str - :param depends_on: Specifies other Kustomizations that this Kustomization depends on. This - Kustomization will not reconcile until all dependencies have completed their reconciliation. - :type depends_on: list[str] - :param timeout: The maximum time to attempt to reconcile the Kustomization on the cluster. - :type timeout: str - :param sync_interval: The interval at which to re-reconcile the Kustomization on the cluster. - :type sync_interval: str - :param retry_interval: The interval at which to re-reconcile the Kustomization on the cluster - in the event of failure on reconciliation. - :type retry_interval: str - :param prune: Enable/disable garbage collections of Kubernetes objects created by this - Kustomization. - :type prune: bool - :param validation: Specify whether to validate the Kubernetes objects referenced in the - Kustomization before applying them to the cluster. Possible values include: "none", "client", - "server". Default value: "none". - :type validation: str or ~azure.mgmt.kubernetesconfiguration.models.KustomizationValidationType - :param force: Enable/disable re-creating Kubernetes resources on the cluster when patching - fails due to an immutable field change. - :type force: bool - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'path': {'key': 'path', 'type': 'str'}, - 'depends_on': {'key': 'dependsOn', 'type': '[str]'}, - 'timeout': {'key': 'timeout', 'type': 'str'}, - 'sync_interval': {'key': 'syncInterval', 'type': 'str'}, - 'retry_interval': {'key': 'retryInterval', 'type': 'str'}, - 'prune': {'key': 'prune', 'type': 'bool'}, - 'validation': {'key': 'validation', 'type': 'str'}, - 'force': {'key': 'force', 'type': 'bool'}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - path: Optional[str] = "", - depends_on: Optional[List[str]] = None, - timeout: Optional[str] = None, - sync_interval: Optional[str] = None, - retry_interval: Optional[str] = None, - prune: Optional[bool] = None, - validation: Optional[Union[str, "KustomizationValidationType"]] = "none", - force: Optional[bool] = None, - **kwargs - ): - super(KustomizationDefinition, self).__init__(**kwargs) - self.name = name - self.path = path - self.depends_on = depends_on - self.timeout = timeout - self.sync_interval = sync_interval - self.retry_interval = retry_interval - self.prune = prune - self.validation = validation - self.force = force - - class OperationStatusList(msrest.serialization.Model): """The async operations in progress, in the cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of async operations in progress, in the cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult] + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperationStatusResult] :ivar next_link: URL to get the next set of Operation Result objects, if any. :vartype next_link: str """ @@ -977,7 +703,7 @@ class OperationStatusResult(msrest.serialization.Model): :param properties: Additional information, if available. :type properties: dict[str, str] :ivar error: If present, details of the operation error. - :vartype error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDetail + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ErrorDetail """ _validation = { @@ -1010,44 +736,6 @@ def __init__( self.error = None -class RepositoryRefDefinition(msrest.serialization.Model): - """The source reference for the GitRepository object. - - :param branch: The git repository branch name to checkout. - :type branch: str - :param tag: The git repository tag name to checkout. This takes precedence over branch. - :type tag: str - :param semver: The semver range used to match against git repository tags. This takes - precedence over tag. - :type semver: str - :param commit: The commit SHA to checkout. This value must be combined with the branch name to - be valid. This takes precedence over semver. - :type commit: str - """ - - _attribute_map = { - 'branch': {'key': 'branch', 'type': 'str'}, - 'tag': {'key': 'tag', 'type': 'str'}, - 'semver': {'key': 'semver', 'type': 'str'}, - 'commit': {'key': 'commit', 'type': 'str'}, - } - - def __init__( - self, - *, - branch: Optional[str] = None, - tag: Optional[str] = None, - semver: Optional[str] = None, - commit: Optional[str] = None, - **kwargs - ): - super(RepositoryRefDefinition, self).__init__(**kwargs) - self.branch = branch - self.tag = tag - self.semver = semver - self.commit = commit - - class ResourceProviderOperation(msrest.serialization.Model): """Supported operation of this resource provider. @@ -1056,7 +744,8 @@ class ResourceProviderOperation(msrest.serialization.Model): :param name: Operation name, in format of {provider}/{resource}/{operation}. :type name: str :param display: Display metadata associated with the operation. - :type display: ~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationDisplay + :type display: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ResourceProviderOperationDisplay :param origin: The intended executor of the operation;governs the display of the operation in the RBAC UX and the audit logs UX. :type origin: str @@ -1132,7 +821,8 @@ class ResourceProviderOperationList(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :param value: List of operations supported by this resource provider. - :type value: list[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperation] + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ResourceProviderOperation] :ivar next_link: URL to the next set of results, if any. :vartype next_link: str """ @@ -1161,9 +851,9 @@ class Scope(msrest.serialization.Model): """Scope of the extension. It can be either Cluster or Namespace; but not both. :param cluster: Specifies that the scope of the extension is Cluster. - :type cluster: ~azure.mgmt.kubernetesconfiguration.models.ScopeCluster + :type cluster: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ScopeCluster :param namespace: Specifies that the scope of the extension is Namespace. - :type namespace: ~azure.mgmt.kubernetesconfiguration.models.ScopeNamespace + :type namespace: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ScopeNamespace """ _attribute_map = { @@ -1242,7 +932,7 @@ class SourceControlConfiguration(ProxyResource): :vartype type: str :ivar system_data: Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. - :vartype system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SystemData :param repository_url: Url of the SourceControl Repository. :type repository_url: str :param operator_namespace: The namespace to which this operator is installed to. Maximum of 253 @@ -1252,7 +942,8 @@ class SourceControlConfiguration(ProxyResource): configuration. :type operator_instance_name: str :param operator_type: Type of the operator. Possible values include: "Flux". - :type operator_type: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorType + :type operator_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperatorType :param operator_params: Any Parameters for the Operator instance in string format. :type operator_params: str :param configuration_protected_settings: Name-value pairs of protected configuration settings @@ -1260,7 +951,8 @@ class SourceControlConfiguration(ProxyResource): :type configuration_protected_settings: dict[str, str] :param operator_scope: Scope at which the operator will be installed. Possible values include: "cluster", "namespace". Default value: "cluster". - :type operator_scope: str or ~azure.mgmt.kubernetesconfiguration.models.OperatorScopeType + :type operator_scope: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperatorScopeType :ivar repository_public_key: Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). :vartype repository_public_key: str @@ -1271,13 +963,14 @@ class SourceControlConfiguration(ProxyResource): :type enable_helm_operator: bool :param helm_operator_properties: Properties for Helm operator. :type helm_operator_properties: - ~azure.mgmt.kubernetesconfiguration.models.HelmOperatorProperties + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.HelmOperatorProperties :ivar provisioning_state: The provisioning state of the resource provider. Possible values include: "Accepted", "Deleting", "Running", "Succeeded", "Failed". :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningStateType + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ProvisioningStateType :ivar compliance_status: Compliance Status of the Configuration. - :vartype compliance_status: ~azure.mgmt.kubernetesconfiguration.models.ComplianceStatus + :vartype compliance_status: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ComplianceStatus """ _validation = { @@ -1348,7 +1041,8 @@ class SourceControlConfigurationList(msrest.serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of Source Control Configurations within a Kubernetes cluster. - :vartype value: list[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration] + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration] :ivar next_link: URL to get the next set of configuration objects, if any. :vartype next_link: str """ @@ -1378,7 +1072,8 @@ class SupportedScopes(msrest.serialization.Model): :param default_scope: Default extension scopes: cluster or namespace. :type default_scope: str :param cluster_scope_settings: Scope settings. - :type cluster_scope_settings: ~azure.mgmt.kubernetesconfiguration.models.ClusterScopeSettings + :type cluster_scope_settings: + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ClusterScopeSettings """ _attribute_map = { @@ -1405,14 +1100,16 @@ class SystemData(msrest.serialization.Model): :type created_by: str :param created_by_type: The type of identity that created the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". - :type created_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :type created_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.CreatedByType :param created_at: The timestamp of resource creation (UTC). :type created_at: ~datetime.datetime :param last_modified_by: The identity that last modified the resource. :type last_modified_by: str :param last_modified_by_type: The type of identity that last modified the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". - :type last_modified_by_type: str or ~azure.mgmt.kubernetesconfiguration.models.CreatedByType + :type last_modified_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.CreatedByType :param last_modified_at: The timestamp of resource last modification (UTC). :type last_modified_at: ~datetime.datetime """ diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py similarity index 80% rename from src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py index ab54da49fa4..d25cb04abdc 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/models/_source_control_configuration_client_enums.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py @@ -67,15 +67,6 @@ class Enum5(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): MANAGED_CLUSTERS = "managedClusters" CONNECTED_CLUSTERS = "connectedClusters" -class KustomizationValidationType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Specify whether to validate the Kubernetes objects referenced in the Kustomization before - applying them to the cluster. - """ - - NONE = "none" - CLIENT = "client" - SERVER = "server" - class LevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Level of the status. """ @@ -125,24 +116,3 @@ class ProvisioningStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)) RUNNING = "Running" SUCCEEDED = "Succeeded" FAILED = "Failed" - -class ScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Scope at which the configuration will be installed. - """ - - CLUSTER = "cluster" - NAMESPACE = "namespace" - -class SourceKindType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Source Kind to pull the configuration data from. - """ - - GIT_REPOSITORY = "GitRepository" - -class SyncStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Compliance state of the cluster object. - """ - - COMPLIANT = "compliant" - NON_COMPLIANT = "non-compliant" - SYNCING = "syncing" diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/__init__.py new file mode 100644 index 00000000000..5f4504b206d --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/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 ._extensions_operations import ExtensionsOperations +from ._operation_status_operations import OperationStatusOperations +from ._cluster_extension_type_operations import ClusterExtensionTypeOperations +from ._cluster_extension_types_operations import ClusterExtensionTypesOperations +from ._extension_type_versions_operations import ExtensionTypeVersionsOperations +from ._location_extension_types_operations import LocationExtensionTypesOperations +from ._source_control_configurations_operations import SourceControlConfigurationsOperations +from ._operations import Operations + +__all__ = [ + 'ExtensionsOperations', + 'OperationStatusOperations', + 'ClusterExtensionTypeOperations', + 'ClusterExtensionTypesOperations', + 'ExtensionTypeVersionsOperations', + 'LocationExtensionTypesOperations', + 'SourceControlConfigurationsOperations', + 'Operations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py similarity index 95% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py index fb463591017..a2998ac9547 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_type_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py @@ -29,7 +29,7 @@ class ClusterExtensionTypeOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -60,17 +60,17 @@ def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_type: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.models.Enum5 + :type cluster_type: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum5 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_type_name: Extension type name. :type extension_type_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExtensionType, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.ExtensionType + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionType :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionType"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py index bc641f3595c..8ba2c2d42e9 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_cluster_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py @@ -30,7 +30,7 @@ class ClusterExtensionTypesOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -59,12 +59,12 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionTypeList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py index 8c8ca358711..bca368e1670 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extension_type_versions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py @@ -30,7 +30,7 @@ class ExtensionTypeVersionsOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -60,7 +60,7 @@ def list( :type extension_type_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionVersionList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionVersionList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionVersionList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionVersionList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py index c0df1e38ae5..a36032c9abf 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_extensions_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py @@ -32,7 +32,7 @@ class ExtensionsOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -129,16 +129,16 @@ def begin_create( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. :type extension_name: str :param extension: Properties necessary to Create an Extension. - :type extension: ~azure.mgmt.kubernetesconfiguration.models.Extension + :type extension: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. @@ -146,7 +146,7 @@ def begin_create( :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either Extension or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.kubernetesconfiguration.models.Extension] + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] @@ -217,17 +217,17 @@ def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. :type extension_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Extension, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.Extension + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Extension :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.Extension"] @@ -348,10 +348,10 @@ def begin_delete( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. @@ -433,15 +433,15 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionsList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionsList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionsList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionsList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py index ff1ae940c42..15282cd28e0 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_location_extension_types_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py @@ -30,7 +30,7 @@ class LocationExtensionTypesOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -57,7 +57,7 @@ def list( :type location: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExtensionTypeList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ExtensionTypeList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ExtensionTypeList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExtensionTypeList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py similarity index 95% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py index 43efd5f16e8..d1987b5f6ed 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operation_status_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py @@ -30,7 +30,7 @@ class OperationStatusOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -62,10 +62,10 @@ def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param extension_name: Name of the Extension. @@ -74,7 +74,7 @@ def get( :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatusResult, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperationStatusResult :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] @@ -138,15 +138,15 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationStatusList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.OperationStatusList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.OperationStatusList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusList"] @@ -154,7 +154,7 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-06-01-preview" + api_version = "2021-05-01-preview" accept = "application/json" def prepare_request(next_link=None): diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operations.py new file mode 100644 index 00000000000..147a262ef47 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operations.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ResourceProviderOperationList"] + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-05-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py similarity index 96% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py index 9d62e711f0e..085294c1476 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_source_control_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py @@ -32,7 +32,7 @@ class SourceControlConfigurationsOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -63,17 +63,17 @@ def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param source_control_configuration_name: Name of the Source Control Configuration. :type source_control_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: SourceControlConfiguration, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] @@ -138,19 +138,19 @@ def create_or_update( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param source_control_configuration_name: Name of the Source Control Configuration. :type source_control_configuration_name: str :param source_control_configuration: Properties necessary to Create KubernetesConfiguration. - :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :type source_control_configuration: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration :keyword callable cls: A custom type or function that will be passed the direct response :return: SourceControlConfiguration, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfiguration"] @@ -276,10 +276,10 @@ def begin_delete( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param source_control_configuration_name: Name of the Source Control Configuration. @@ -357,15 +357,15 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SourceControlConfigurationList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfigurationList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.SourceControlConfigurationList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SourceControlConfigurationList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/__init__.py new file mode 100644 index 00000000000..f13062376d7 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/__init__.py @@ -0,0 +1,19 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['SourceControlConfigurationClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_configuration.py new file mode 100644 index 00000000000..27f67e28de4 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_configuration.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-06-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py new file mode 100644 index 00000000000..ae2faffc61c --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py @@ -0,0 +1,104 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import FluxConfigurationsOperations +from .operations import FluxConfigOperationStatusOperations +from .operations import Operations +from .operations import OperationStatusOperations +from . import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar flux_configurations: FluxConfigurationsOperations operations + :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.operations.FluxConfigurationsOperations + :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations + :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.operations.FluxConfigOperationStatusOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.operations.Operations + :ivar operation_status: OperationStatusOperations operations + :vartype operation_status: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.operations.OperationStatusOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.flux_configurations = FluxConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.flux_config_operation_status = FluxConfigOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.operation_status = OperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + + def _send_request(self, http_request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.HttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> SourceControlConfigurationClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_version.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_version.py new file mode 100644 index 00000000000..e5754a47ce6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_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/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/__init__.py new file mode 100644 index 00000000000..ba52c91a7ba --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/__init__.py @@ -0,0 +1,10 @@ +# 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 ._source_control_configuration_client import SourceControlConfigurationClient +__all__ = ['SourceControlConfigurationClient'] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_configuration.py new file mode 100644 index 00000000000..510c9921e82 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_configuration.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. + + 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. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = "2021-06-01-preview" + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py new file mode 100644 index 00000000000..5995666aeb2 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py @@ -0,0 +1,97 @@ +# 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, Optional, TYPE_CHECKING + +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + +from ._configuration import SourceControlConfigurationClientConfiguration +from .operations import FluxConfigurationsOperations +from .operations import FluxConfigOperationStatusOperations +from .operations import Operations +from .operations import OperationStatusOperations +from .. import models + + +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. + + :ivar flux_configurations: FluxConfigurationsOperations operations + :vartype flux_configurations: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.aio.operations.FluxConfigurationsOperations + :ivar flux_config_operation_status: FluxConfigOperationStatusOperations operations + :vartype flux_config_operation_status: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.aio.operations.FluxConfigOperationStatusOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.aio.operations.Operations + :ivar operation_status: OperationStatusOperations operations + :vartype operation_status: azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.aio.operations.OperationStatusOperations + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. + :type subscription_id: str + :param str base_url: Service URL + :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: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + self.flux_configurations = FluxConfigurationsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.flux_config_operation_status = FluxConfigOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations( + self._client, self._config, self._serialize, self._deserialize) + self.operation_status = OperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize) + + async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + :param http_request: The network request you want to make. Required. + :type http_request: ~azure.core.pipeline.transport.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + """ + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + } + http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + stream = kwargs.pop("stream", True) + pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) + return pipeline_response.http_response + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "SourceControlConfigurationClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py new file mode 100644 index 00000000000..901f9c1b2c1 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# 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 ._flux_configurations_operations import FluxConfigurationsOperations +from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations +from ._operations import Operations +from ._operation_status_operations import OperationStatusOperations + +__all__ = [ + 'FluxConfigurationsOperations', + 'FluxConfigOperationStatusOperations', + 'Operations', + 'OperationStatusOperations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_config_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py similarity index 95% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_config_operation_status_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py index b8fd3066fea..66a6ebbddd6 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_config_operation_status_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py @@ -25,7 +25,7 @@ class FluxConfigOperationStatusOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -56,10 +56,10 @@ async def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. @@ -68,7 +68,7 @@ async def get( :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatusResult, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.OperationStatusResult :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py index e6c7f967650..e7ec3bcdcc7 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_flux_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py @@ -28,7 +28,7 @@ class FluxConfigurationsOperations: instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -58,17 +58,17 @@ async def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. :type flux_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: FluxConfiguration, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] @@ -192,16 +192,16 @@ async def begin_create_or_update( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. :type flux_configuration_name: str :param flux_configuration: Properties necessary to Create a FluxConfiguration. - :type flux_configuration: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :type flux_configuration: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. @@ -209,7 +209,7 @@ async def begin_create_or_update( :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either FluxConfiguration or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] @@ -335,10 +335,10 @@ async def begin_delete( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. @@ -419,15 +419,15 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FluxConfigurationsList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.models.FluxConfigurationsList] + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfigurationsList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfigurationsList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py new file mode 100644 index 00000000000..d10c6cae290 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py @@ -0,0 +1,127 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class OperationStatusOperations: + """OperationStatusOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name: str, + cluster_rp: Union[str, "_models.Enum0"], + cluster_resource_name: Union[str, "_models.Enum1"], + cluster_name: str, + **kwargs: Any + ) -> AsyncIterable["_models.OperationStatusList"]: + """List Async Operations, currently in progress, in a cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either OperationStatusList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.OperationStatusList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('OperationStatusList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py new file mode 100644 index 00000000000..39439755239 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py @@ -0,0 +1,105 @@ +# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class Operations: + """Operations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs: Any + ) -> AsyncIterable["_models.ResourceProviderOperationList"]: + """List all the available operations the KubernetesConfiguration resource provider supports. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ResourceProviderOperationList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('ResourceProviderOperationList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/__init__.py new file mode 100644 index 00000000000..0f67521b906 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/__init__.py @@ -0,0 +1,80 @@ +# 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. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import ErrorAdditionalInfo + from ._models_py3 import ErrorDetail + from ._models_py3 import ErrorResponse + from ._models_py3 import FluxConfiguration + from ._models_py3 import FluxConfigurationsList + from ._models_py3 import GitRepositoryDefinition + from ._models_py3 import KustomizationDefinition + from ._models_py3 import OperationStatusList + from ._models_py3 import OperationStatusResult + from ._models_py3 import ProxyResource + from ._models_py3 import RepositoryRefDefinition + from ._models_py3 import Resource + from ._models_py3 import ResourceProviderOperation + from ._models_py3 import ResourceProviderOperationDisplay + from ._models_py3 import ResourceProviderOperationList + from ._models_py3 import SystemData +except (SyntaxError, ImportError): + from ._models import ErrorAdditionalInfo # type: ignore + from ._models import ErrorDetail # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import FluxConfiguration # type: ignore + from ._models import FluxConfigurationsList # type: ignore + from ._models import GitRepositoryDefinition # type: ignore + from ._models import KustomizationDefinition # type: ignore + from ._models import OperationStatusList # type: ignore + from ._models import OperationStatusResult # type: ignore + from ._models import ProxyResource # type: ignore + from ._models import RepositoryRefDefinition # type: ignore + from ._models import Resource # type: ignore + from ._models import ResourceProviderOperation # type: ignore + from ._models import ResourceProviderOperationDisplay # type: ignore + from ._models import ResourceProviderOperationList # type: ignore + from ._models import SystemData # type: ignore + +from ._source_control_configuration_client_enums import ( + CreatedByType, + Enum0, + Enum1, + KustomizationValidationType, + ProvisioningState, + ScopeType, + SourceKindType, + SyncStateType, +) + +__all__ = [ + 'ErrorAdditionalInfo', + 'ErrorDetail', + 'ErrorResponse', + 'FluxConfiguration', + 'FluxConfigurationsList', + 'GitRepositoryDefinition', + 'KustomizationDefinition', + 'OperationStatusList', + 'OperationStatusResult', + 'ProxyResource', + 'RepositoryRefDefinition', + 'Resource', + 'ResourceProviderOperation', + 'ResourceProviderOperationDisplay', + 'ResourceProviderOperationList', + 'SystemData', + 'CreatedByType', + 'Enum0', + 'Enum1', + 'KustomizationValidationType', + 'ProvisioningState', + 'ScopeType', + 'SourceKindType', + 'SyncStateType', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models.py new file mode 100644 index 00000000000..f5c6758e993 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models.py @@ -0,0 +1,692 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class ErrorAdditionalInfo(msrest.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: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(msrest.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.kubernetesconfiguration.v2021_06_01_preview.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.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 + ): + super(ErrorDetail, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(msrest.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.). + + :param error: The error object. + :type error: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ErrorDetail + """ + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = kwargs.get('error', None) + + +class Resource(msrest.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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class 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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class FluxConfiguration(ProxyResource): + """The Flux Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.SystemData + :param scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type scope: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ScopeType + :param namespace: The namespace to which this configuration is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type namespace: str + :param source_kind: Source Kind to pull the configuration data from. Possible values include: + "GitRepository". Default value: "GitRepository". + :type source_kind: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.SourceKindType + :param suspend: Whether this configuration should suspend its reconciliation of its + kustomizations and sources. + :type suspend: bool + :param git_repository: Parameters to reconcile to the GitRepository source kind type. + :type git_repository: + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.GitRepositoryDefinition + :param kustomizations: Array of kustomizations used to reconcile the artifact pulled by the + source type on the cluster. + :type kustomizations: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.KustomizationDefinition] + :param configuration_protected_settings: Key-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :ivar statuses: Statuses of the Flux Kubernetes resources created by the fluxConfiguration or + created by the managed objects provisioned by the fluxConfiguration. + :vartype statuses: list[dict[str, any]] + :ivar repository_public_key: Public Key associated with this fluxConfiguration (either + generated within the cluster or provided by the user). + :vartype repository_public_key: str + :ivar last_synced_time: Datetime the fluxConfiguration has been synced with the Azure control + plane. + :vartype last_synced_time: str + :ivar last_synced_commit: Branch and SHA of the last source commit synced with the cluster. + :vartype last_synced_commit: str + :ivar last_config_applied_time: Datetime the fluxConfiguration was last applied. + :vartype last_config_applied_time: str + :ivar sync_state: Combined status of the Flux Kubernetes resources created by the + fluxConfiguration or created by the managed objects. Possible values include: "compliant", + "non-compliant", "pending", "suspended", "unknown". Default value: "pending". + :vartype sync_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.SyncStateType + :ivar provisioning_state: Status of the creation of the fluxConfiguration. Possible values + include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ProvisioningState + :ivar message: Error message returned to the user in the case of provisioning failure. + :vartype message: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'statuses': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'last_synced_time': {'readonly': True}, + 'last_synced_commit': {'readonly': True}, + 'last_config_applied_time': {'readonly': True}, + 'sync_state': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'message': {'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'}, + 'scope': {'key': 'properties.scope', 'type': 'str'}, + 'namespace': {'key': 'properties.namespace', 'type': 'str'}, + 'source_kind': {'key': 'properties.sourceKind', 'type': 'str'}, + 'suspend': {'key': 'properties.suspend', 'type': 'bool'}, + 'git_repository': {'key': 'properties.gitRepository', 'type': 'GitRepositoryDefinition'}, + 'kustomizations': {'key': 'properties.kustomizations', 'type': '[KustomizationDefinition]'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'statuses': {'key': 'properties.statuses', 'type': '[{object}]'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'last_synced_time': {'key': 'properties.lastSyncedTime', 'type': 'str'}, + 'last_synced_commit': {'key': 'properties.lastSyncedCommit', 'type': 'str'}, + 'last_config_applied_time': {'key': 'properties.lastConfigAppliedTime', 'type': 'str'}, + 'sync_state': {'key': 'properties.syncState', 'type': 'str'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'message': {'key': 'properties.message', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FluxConfiguration, self).__init__(**kwargs) + self.system_data = None + self.scope = kwargs.get('scope', "cluster") + self.namespace = kwargs.get('namespace', "default") + self.source_kind = kwargs.get('source_kind', "GitRepository") + self.suspend = kwargs.get('suspend', False) + self.git_repository = kwargs.get('git_repository', None) + self.kustomizations = kwargs.get('kustomizations', None) + self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) + self.statuses = None + self.repository_public_key = None + self.last_synced_time = None + self.last_synced_commit = None + self.last_config_applied_time = None + self.sync_state = None + self.provisioning_state = None + self.message = None + + +class FluxConfigurationsList(msrest.serialization.Model): + """Result of the request to list Flux Configurations. It contains a list of FluxConfiguration objects and a 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 Flux Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FluxConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FluxConfigurationsList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class GitRepositoryDefinition(msrest.serialization.Model): + """Parameters to reconcile to the GitRepository source kind type. + + :param url: The URL to sync for the flux configuration git repository. + :type url: str + :param timeout_in_seconds: The maximum time to attempt to reconcile the cluster git repository + source with the remote. + :type timeout_in_seconds: long + :param sync_interval_in_seconds: The interval at which to re-reconcile the cluster git + repository source with the remote. + :type sync_interval_in_seconds: long + :param repository_ref: The source reference for the GitRepository object. + :type repository_ref: + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.RepositoryRefDefinition + :param ssh_known_hosts: Base64-encoded known_hosts value containing public SSH keys required to + access private git repositories over SSH. + :type ssh_known_hosts: str + :param https_user: HTTPS username used to access private git repositories over HTTPS. + :type https_user: str + :param local_auth_ref: Name of a local secret on the Kubernetes cluster to use as the + authentication secret rather than the managed or user-provided configuration secrets. + :type local_auth_ref: str + """ + + _attribute_map = { + 'url': {'key': 'url', 'type': 'str'}, + 'timeout_in_seconds': {'key': 'timeoutInSeconds', 'type': 'long'}, + 'sync_interval_in_seconds': {'key': 'syncIntervalInSeconds', 'type': 'long'}, + 'repository_ref': {'key': 'repositoryRef', 'type': 'RepositoryRefDefinition'}, + 'ssh_known_hosts': {'key': 'sshKnownHosts', 'type': 'str'}, + 'https_user': {'key': 'httpsUser', 'type': 'str'}, + 'local_auth_ref': {'key': 'localAuthRef', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(GitRepositoryDefinition, self).__init__(**kwargs) + self.url = kwargs.get('url', None) + self.timeout_in_seconds = kwargs.get('timeout_in_seconds', 600) + self.sync_interval_in_seconds = kwargs.get('sync_interval_in_seconds', 600) + self.repository_ref = kwargs.get('repository_ref', None) + self.ssh_known_hosts = kwargs.get('ssh_known_hosts', None) + self.https_user = kwargs.get('https_user', None) + self.local_auth_ref = kwargs.get('local_auth_ref', None) + + +class KustomizationDefinition(msrest.serialization.Model): + """KustomizationDefinition. + + :param name: The name of the Kustomization object to create on the cluster. + :type name: str + :param path: The path in the source reference to reconcile on the cluster. + :type path: str + :param depends_on: Specifies other Kustomizations that this Kustomization depends on. This + Kustomization will not reconcile until all dependencies have completed their reconciliation. + :type depends_on: list[str] + :param timeout_in_seconds: The maximum time to attempt to reconcile the Kustomization on the + cluster. + :type timeout_in_seconds: long + :param sync_interval_in_seconds: The interval at which to re-reconcile the Kustomization on the + cluster. + :type sync_interval_in_seconds: long + :param retry_interval_in_seconds: The interval at which to re-reconcile the Kustomization on + the cluster in the event of failure on reconciliation. + :type retry_interval_in_seconds: long + :param prune: Enable/disable garbage collections of Kubernetes objects created by this + Kustomization. + :type prune: bool + :param validation: Specify whether to validate the Kubernetes objects referenced in the + Kustomization before applying them to the cluster. Possible values include: "none", "client", + "server". Default value: "none". + :type validation: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.KustomizationValidationType + :param force: Enable/disable re-creating Kubernetes resources on the cluster when patching + fails due to an immutable field change. + :type force: bool + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'path': {'key': 'path', 'type': 'str'}, + 'depends_on': {'key': 'dependsOn', 'type': '[str]'}, + 'timeout_in_seconds': {'key': 'timeoutInSeconds', 'type': 'long'}, + 'sync_interval_in_seconds': {'key': 'syncIntervalInSeconds', 'type': 'long'}, + 'retry_interval_in_seconds': {'key': 'retryIntervalInSeconds', 'type': 'long'}, + 'prune': {'key': 'prune', 'type': 'bool'}, + 'validation': {'key': 'validation', 'type': 'str'}, + 'force': {'key': 'force', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(KustomizationDefinition, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.path = kwargs.get('path', "") + self.depends_on = kwargs.get('depends_on', None) + self.timeout_in_seconds = kwargs.get('timeout_in_seconds', 600) + self.sync_interval_in_seconds = kwargs.get('sync_interval_in_seconds', 600) + self.retry_interval_in_seconds = kwargs.get('retry_interval_in_seconds', None) + self.prune = kwargs.get('prune', None) + self.validation = kwargs.get('validation', "none") + self.force = kwargs.get('force', None) + + +class OperationStatusList(msrest.serialization.Model): + """The async operations in progress, in the cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of async operations in progress, in the cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.OperationStatusResult] + :ivar next_link: URL to get the next set of Operation Result objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[OperationStatusResult]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationStatusList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class OperationStatusResult(msrest.serialization.Model): + """The current status of an async operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param id: Fully qualified ID for the async operation. + :type id: str + :param name: Name of the async operation. + :type name: str + :param status: Required. Operation status. + :type status: str + :param properties: Additional information, if available. + :type properties: dict[str, str] + :ivar error: If present, details of the operation error. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ErrorDetail + """ + + _validation = { + 'status': {'required': True}, + 'error': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'status': {'key': 'status', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{str}'}, + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationStatusResult, self).__init__(**kwargs) + self.id = kwargs.get('id', None) + self.name = kwargs.get('name', None) + self.status = kwargs['status'] + self.properties = kwargs.get('properties', None) + self.error = None + + +class RepositoryRefDefinition(msrest.serialization.Model): + """The source reference for the GitRepository object. + + :param branch: The git repository branch name to checkout. + :type branch: str + :param tag: The git repository tag name to checkout. This takes precedence over branch. + :type tag: str + :param semver: The semver range used to match against git repository tags. This takes + precedence over tag. + :type semver: str + :param commit: The commit SHA to checkout. This value must be combined with the branch name to + be valid. This takes precedence over semver. + :type commit: str + """ + + _attribute_map = { + 'branch': {'key': 'branch', 'type': 'str'}, + 'tag': {'key': 'tag', 'type': 'str'}, + 'semver': {'key': 'semver', 'type': 'str'}, + 'commit': {'key': 'commit', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RepositoryRefDefinition, self).__init__(**kwargs) + self.branch = kwargs.get('branch', None) + self.tag = kwargs.get('tag', None) + self.semver = kwargs.get('semver', None) + self.commit = kwargs.get('commit', None) + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ResourceProviderOperationDisplay + :param origin: The intended executor of the operation;governs the display of the operation in + the RBAC UX and the audit logs UX. + :type origin: str + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = kwargs.get('name', None) + self.display = kwargs.get('display', None) + self.origin = kwargs.get('origin', None) + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _attribute_map = { + 'provider': {'key': 'provider', 'type': 'str'}, + 'resource': {'key': 'resource', 'type': 'str'}, + 'operation': {'key': 'operation', 'type': 'str'}, + 'description': {'key': 'description', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = kwargs.get('provider', None) + self.resource = kwargs.get('resource', None) + self.operation = kwargs.get('operation', None) + self.description = kwargs.get('description', None) + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type 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, + **kwargs + ): + super(SystemData, self).__init__(**kwargs) + self.created_by = kwargs.get('created_by', None) + self.created_by_type = kwargs.get('created_by_type', None) + self.created_at = kwargs.get('created_at', None) + self.last_modified_by = kwargs.get('last_modified_by', None) + self.last_modified_by_type = kwargs.get('last_modified_by_type', None) + self.last_modified_at = kwargs.get('last_modified_at', None) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models_py3.py new file mode 100644 index 00000000000..36d8a717508 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models_py3.py @@ -0,0 +1,753 @@ +# 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 datetime +from typing import Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._source_control_configuration_client_enums import * + + +class ErrorAdditionalInfo(msrest.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: any + """ + + _validation = { + 'type': {'readonly': True}, + 'info': {'readonly': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + 'info': {'key': 'info', 'type': 'object'}, + } + + def __init__( + self, + **kwargs + ): + super(ErrorAdditionalInfo, self).__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(msrest.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.kubernetesconfiguration.v2021_06_01_preview.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.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 + ): + super(ErrorDetail, self).__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(msrest.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.). + + :param error: The error object. + :type error: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ErrorDetail + """ + + _attribute_map = { + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + *, + error: Optional["ErrorDetail"] = None, + **kwargs + ): + super(ErrorResponse, self).__init__(**kwargs) + self.error = error + + +class Resource(msrest.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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(Resource, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class 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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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 + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(ProxyResource, self).__init__(**kwargs) + + +class FluxConfiguration(ProxyResource): + """The Flux Configuration object returned in Get & Put response. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :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: Top level metadata + https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources. + :vartype system_data: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.SystemData + :param scope: Scope at which the operator will be installed. Possible values include: + "cluster", "namespace". Default value: "cluster". + :type scope: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ScopeType + :param namespace: The namespace to which this configuration is installed to. Maximum of 253 + lower case alphanumeric characters, hyphen and period only. + :type namespace: str + :param source_kind: Source Kind to pull the configuration data from. Possible values include: + "GitRepository". Default value: "GitRepository". + :type source_kind: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.SourceKindType + :param suspend: Whether this configuration should suspend its reconciliation of its + kustomizations and sources. + :type suspend: bool + :param git_repository: Parameters to reconcile to the GitRepository source kind type. + :type git_repository: + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.GitRepositoryDefinition + :param kustomizations: Array of kustomizations used to reconcile the artifact pulled by the + source type on the cluster. + :type kustomizations: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.KustomizationDefinition] + :param configuration_protected_settings: Key-value pairs of protected configuration settings + for the configuration. + :type configuration_protected_settings: dict[str, str] + :ivar statuses: Statuses of the Flux Kubernetes resources created by the fluxConfiguration or + created by the managed objects provisioned by the fluxConfiguration. + :vartype statuses: list[dict[str, any]] + :ivar repository_public_key: Public Key associated with this fluxConfiguration (either + generated within the cluster or provided by the user). + :vartype repository_public_key: str + :ivar last_synced_time: Datetime the fluxConfiguration has been synced with the Azure control + plane. + :vartype last_synced_time: str + :ivar last_synced_commit: Branch and SHA of the last source commit synced with the cluster. + :vartype last_synced_commit: str + :ivar last_config_applied_time: Datetime the fluxConfiguration was last applied. + :vartype last_config_applied_time: str + :ivar sync_state: Combined status of the Flux Kubernetes resources created by the + fluxConfiguration or created by the managed objects. Possible values include: "compliant", + "non-compliant", "pending", "suspended", "unknown". Default value: "pending". + :vartype sync_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.SyncStateType + :ivar provisioning_state: Status of the creation of the fluxConfiguration. Possible values + include: "Succeeded", "Failed", "Canceled", "Creating", "Updating", "Deleting". + :vartype provisioning_state: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ProvisioningState + :ivar message: Error message returned to the user in the case of provisioning failure. + :vartype message: str + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + 'system_data': {'readonly': True}, + 'statuses': {'readonly': True}, + 'repository_public_key': {'readonly': True}, + 'last_synced_time': {'readonly': True}, + 'last_synced_commit': {'readonly': True}, + 'last_config_applied_time': {'readonly': True}, + 'sync_state': {'readonly': True}, + 'provisioning_state': {'readonly': True}, + 'message': {'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'}, + 'scope': {'key': 'properties.scope', 'type': 'str'}, + 'namespace': {'key': 'properties.namespace', 'type': 'str'}, + 'source_kind': {'key': 'properties.sourceKind', 'type': 'str'}, + 'suspend': {'key': 'properties.suspend', 'type': 'bool'}, + 'git_repository': {'key': 'properties.gitRepository', 'type': 'GitRepositoryDefinition'}, + 'kustomizations': {'key': 'properties.kustomizations', 'type': '[KustomizationDefinition]'}, + 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, + 'statuses': {'key': 'properties.statuses', 'type': '[{object}]'}, + 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, + 'last_synced_time': {'key': 'properties.lastSyncedTime', 'type': 'str'}, + 'last_synced_commit': {'key': 'properties.lastSyncedCommit', 'type': 'str'}, + 'last_config_applied_time': {'key': 'properties.lastConfigAppliedTime', 'type': 'str'}, + 'sync_state': {'key': 'properties.syncState', 'type': 'str'}, + 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + 'message': {'key': 'properties.message', 'type': 'str'}, + } + + def __init__( + self, + *, + scope: Optional[Union[str, "ScopeType"]] = "cluster", + namespace: Optional[str] = "default", + source_kind: Optional[Union[str, "SourceKindType"]] = "GitRepository", + suspend: Optional[bool] = False, + git_repository: Optional["GitRepositoryDefinition"] = None, + kustomizations: Optional[List["KustomizationDefinition"]] = None, + configuration_protected_settings: Optional[Dict[str, str]] = None, + **kwargs + ): + super(FluxConfiguration, self).__init__(**kwargs) + self.system_data = None + self.scope = scope + self.namespace = namespace + self.source_kind = source_kind + self.suspend = suspend + self.git_repository = git_repository + self.kustomizations = kustomizations + self.configuration_protected_settings = configuration_protected_settings + self.statuses = None + self.repository_public_key = None + self.last_synced_time = None + self.last_synced_commit = None + self.last_config_applied_time = None + self.sync_state = None + self.provisioning_state = None + self.message = None + + +class FluxConfigurationsList(msrest.serialization.Model): + """Result of the request to list Flux Configurations. It contains a list of FluxConfiguration objects and a 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 Flux Configurations within a Kubernetes cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration] + :ivar next_link: URL to get the next set of configuration objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[FluxConfiguration]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FluxConfigurationsList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class GitRepositoryDefinition(msrest.serialization.Model): + """Parameters to reconcile to the GitRepository source kind type. + + :param url: The URL to sync for the flux configuration git repository. + :type url: str + :param timeout_in_seconds: The maximum time to attempt to reconcile the cluster git repository + source with the remote. + :type timeout_in_seconds: long + :param sync_interval_in_seconds: The interval at which to re-reconcile the cluster git + repository source with the remote. + :type sync_interval_in_seconds: long + :param repository_ref: The source reference for the GitRepository object. + :type repository_ref: + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.RepositoryRefDefinition + :param ssh_known_hosts: Base64-encoded known_hosts value containing public SSH keys required to + access private git repositories over SSH. + :type ssh_known_hosts: str + :param https_user: HTTPS username used to access private git repositories over HTTPS. + :type https_user: str + :param local_auth_ref: Name of a local secret on the Kubernetes cluster to use as the + authentication secret rather than the managed or user-provided configuration secrets. + :type local_auth_ref: str + """ + + _attribute_map = { + 'url': {'key': 'url', 'type': 'str'}, + 'timeout_in_seconds': {'key': 'timeoutInSeconds', 'type': 'long'}, + 'sync_interval_in_seconds': {'key': 'syncIntervalInSeconds', 'type': 'long'}, + 'repository_ref': {'key': 'repositoryRef', 'type': 'RepositoryRefDefinition'}, + 'ssh_known_hosts': {'key': 'sshKnownHosts', 'type': 'str'}, + 'https_user': {'key': 'httpsUser', 'type': 'str'}, + 'local_auth_ref': {'key': 'localAuthRef', 'type': 'str'}, + } + + def __init__( + self, + *, + url: Optional[str] = None, + timeout_in_seconds: Optional[int] = 600, + sync_interval_in_seconds: Optional[int] = 600, + repository_ref: Optional["RepositoryRefDefinition"] = None, + ssh_known_hosts: Optional[str] = None, + https_user: Optional[str] = None, + local_auth_ref: Optional[str] = None, + **kwargs + ): + super(GitRepositoryDefinition, self).__init__(**kwargs) + self.url = url + self.timeout_in_seconds = timeout_in_seconds + self.sync_interval_in_seconds = sync_interval_in_seconds + self.repository_ref = repository_ref + self.ssh_known_hosts = ssh_known_hosts + self.https_user = https_user + self.local_auth_ref = local_auth_ref + + +class KustomizationDefinition(msrest.serialization.Model): + """KustomizationDefinition. + + :param name: The name of the Kustomization object to create on the cluster. + :type name: str + :param path: The path in the source reference to reconcile on the cluster. + :type path: str + :param depends_on: Specifies other Kustomizations that this Kustomization depends on. This + Kustomization will not reconcile until all dependencies have completed their reconciliation. + :type depends_on: list[str] + :param timeout_in_seconds: The maximum time to attempt to reconcile the Kustomization on the + cluster. + :type timeout_in_seconds: long + :param sync_interval_in_seconds: The interval at which to re-reconcile the Kustomization on the + cluster. + :type sync_interval_in_seconds: long + :param retry_interval_in_seconds: The interval at which to re-reconcile the Kustomization on + the cluster in the event of failure on reconciliation. + :type retry_interval_in_seconds: long + :param prune: Enable/disable garbage collections of Kubernetes objects created by this + Kustomization. + :type prune: bool + :param validation: Specify whether to validate the Kubernetes objects referenced in the + Kustomization before applying them to the cluster. Possible values include: "none", "client", + "server". Default value: "none". + :type validation: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.KustomizationValidationType + :param force: Enable/disable re-creating Kubernetes resources on the cluster when patching + fails due to an immutable field change. + :type force: bool + """ + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'path': {'key': 'path', 'type': 'str'}, + 'depends_on': {'key': 'dependsOn', 'type': '[str]'}, + 'timeout_in_seconds': {'key': 'timeoutInSeconds', 'type': 'long'}, + 'sync_interval_in_seconds': {'key': 'syncIntervalInSeconds', 'type': 'long'}, + 'retry_interval_in_seconds': {'key': 'retryIntervalInSeconds', 'type': 'long'}, + 'prune': {'key': 'prune', 'type': 'bool'}, + 'validation': {'key': 'validation', 'type': 'str'}, + 'force': {'key': 'force', 'type': 'bool'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + path: Optional[str] = "", + depends_on: Optional[List[str]] = None, + timeout_in_seconds: Optional[int] = 600, + sync_interval_in_seconds: Optional[int] = 600, + retry_interval_in_seconds: Optional[int] = None, + prune: Optional[bool] = None, + validation: Optional[Union[str, "KustomizationValidationType"]] = "none", + force: Optional[bool] = None, + **kwargs + ): + super(KustomizationDefinition, self).__init__(**kwargs) + self.name = name + self.path = path + self.depends_on = depends_on + self.timeout_in_seconds = timeout_in_seconds + self.sync_interval_in_seconds = sync_interval_in_seconds + self.retry_interval_in_seconds = retry_interval_in_seconds + self.prune = prune + self.validation = validation + self.force = force + + +class OperationStatusList(msrest.serialization.Model): + """The async operations in progress, in the cluster. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of async operations in progress, in the cluster. + :vartype value: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.OperationStatusResult] + :ivar next_link: URL to get the next set of Operation Result objects, if any. + :vartype next_link: str + """ + + _validation = { + 'value': {'readonly': True}, + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[OperationStatusResult]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(OperationStatusList, self).__init__(**kwargs) + self.value = None + self.next_link = None + + +class OperationStatusResult(msrest.serialization.Model): + """The current status of an async operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :param id: Fully qualified ID for the async operation. + :type id: str + :param name: Name of the async operation. + :type name: str + :param status: Required. Operation status. + :type status: str + :param properties: Additional information, if available. + :type properties: dict[str, str] + :ivar error: If present, details of the operation error. + :vartype error: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ErrorDetail + """ + + _validation = { + 'status': {'required': True}, + 'error': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'status': {'key': 'status', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': '{str}'}, + 'error': {'key': 'error', 'type': 'ErrorDetail'}, + } + + def __init__( + self, + *, + status: str, + id: Optional[str] = None, + name: Optional[str] = None, + properties: Optional[Dict[str, str]] = None, + **kwargs + ): + super(OperationStatusResult, self).__init__(**kwargs) + self.id = id + self.name = name + self.status = status + self.properties = properties + self.error = None + + +class RepositoryRefDefinition(msrest.serialization.Model): + """The source reference for the GitRepository object. + + :param branch: The git repository branch name to checkout. + :type branch: str + :param tag: The git repository tag name to checkout. This takes precedence over branch. + :type tag: str + :param semver: The semver range used to match against git repository tags. This takes + precedence over tag. + :type semver: str + :param commit: The commit SHA to checkout. This value must be combined with the branch name to + be valid. This takes precedence over semver. + :type commit: str + """ + + _attribute_map = { + 'branch': {'key': 'branch', 'type': 'str'}, + 'tag': {'key': 'tag', 'type': 'str'}, + 'semver': {'key': 'semver', 'type': 'str'}, + 'commit': {'key': 'commit', 'type': 'str'}, + } + + def __init__( + self, + *, + branch: Optional[str] = None, + tag: Optional[str] = None, + semver: Optional[str] = None, + commit: Optional[str] = None, + **kwargs + ): + super(RepositoryRefDefinition, self).__init__(**kwargs) + self.branch = branch + self.tag = tag + self.semver = semver + self.commit = commit + + +class ResourceProviderOperation(msrest.serialization.Model): + """Supported operation of this resource provider. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param name: Operation name, in format of {provider}/{resource}/{operation}. + :type name: str + :param display: Display metadata associated with the operation. + :type display: + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ResourceProviderOperationDisplay + :param origin: The intended executor of the operation;governs the display of the operation in + the RBAC UX and the audit logs UX. + :type origin: str + :ivar is_data_action: The flag that indicates whether the operation applies to data plane. + :vartype is_data_action: bool + """ + + _validation = { + 'is_data_action': {'readonly': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, + 'origin': {'key': 'origin', 'type': 'str'}, + 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["ResourceProviderOperationDisplay"] = None, + origin: Optional[str] = None, + **kwargs + ): + super(ResourceProviderOperation, self).__init__(**kwargs) + self.name = name + self.display = display + self.origin = origin + self.is_data_action = None + + +class ResourceProviderOperationDisplay(msrest.serialization.Model): + """Display metadata associated with the operation. + + :param provider: Resource provider: Microsoft KubernetesConfiguration. + :type provider: str + :param resource: Resource on which the operation is performed. + :type resource: str + :param operation: Type of operation: get, read, delete, etc. + :type operation: str + :param description: Description of this operation. + :type description: str + """ + + _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, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs + ): + super(ResourceProviderOperationDisplay, self).__init__(**kwargs) + self.provider = provider + self.resource = resource + self.operation = operation + self.description = description + + +class ResourceProviderOperationList(msrest.serialization.Model): + """Result of the request to list operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param value: List of operations supported by this resource provider. + :type value: + list[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ResourceProviderOperation] + :ivar next_link: URL to the next set of results, if any. + :vartype next_link: str + """ + + _validation = { + 'next_link': {'readonly': True}, + } + + _attribute_map = { + 'value': {'key': 'value', 'type': '[ResourceProviderOperation]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["ResourceProviderOperation"]] = None, + **kwargs + ): + super(ResourceProviderOperationList, self).__init__(**kwargs) + self.value = value + self.next_link = None + + +class SystemData(msrest.serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :param created_by: The identity that created the resource. + :type created_by: str + :param created_by_type: The type of identity that created the resource. Possible values + include: "User", "Application", "ManagedIdentity", "Key". + :type created_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.CreatedByType + :param created_at: The timestamp of resource creation (UTC). + :type created_at: ~datetime.datetime + :param last_modified_by: The identity that last modified the resource. + :type last_modified_by: str + :param last_modified_by_type: The type of identity that last modified the resource. Possible + values include: "User", "Application", "ManagedIdentity", "Key". + :type last_modified_by_type: str or + ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.CreatedByType + :param last_modified_at: The timestamp of resource last modification (UTC). + :type 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, "CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs + ): + super(SystemData, self).__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/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py new file mode 100644 index 00000000000..e1f3f32f4fb --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py @@ -0,0 +1,89 @@ +# 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, EnumMeta +from six import with_metaclass + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class CreatedByType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The type of identity that created the resource. + """ + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + +class Enum0(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MICROSOFT_CONTAINER_SERVICE = "Microsoft.ContainerService" + MICROSOFT_KUBERNETES = "Microsoft.Kubernetes" + +class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + + MANAGED_CLUSTERS = "managedClusters" + CONNECTED_CLUSTERS = "connectedClusters" + +class KustomizationValidationType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Specify whether to validate the Kubernetes objects referenced in the Kustomization before + applying them to the cluster. + """ + + NONE = "none" + CLIENT = "client" + SERVER = "server" + +class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The provisioning state of the resource. + """ + + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + CREATING = "Creating" + UPDATING = "Updating" + DELETING = "Deleting" + +class ScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Scope at which the configuration will be installed. + """ + + CLUSTER = "cluster" + NAMESPACE = "namespace" + +class SourceKindType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Source Kind to pull the configuration data from. + """ + + GIT_REPOSITORY = "GitRepository" + +class SyncStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Compliance state of the cluster object. + """ + + COMPLIANT = "compliant" + NON_COMPLIANT = "non-compliant" + PENDING = "pending" + SUSPENDED = "suspended" + UNKNOWN = "unknown" diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/__init__.py new file mode 100644 index 00000000000..901f9c1b2c1 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/__init__.py @@ -0,0 +1,19 @@ +# 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 ._flux_configurations_operations import FluxConfigurationsOperations +from ._flux_config_operation_status_operations import FluxConfigOperationStatusOperations +from ._operations import Operations +from ._operation_status_operations import OperationStatusOperations + +__all__ = [ + 'FluxConfigurationsOperations', + 'FluxConfigOperationStatusOperations', + 'Operations', + 'OperationStatusOperations', +] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_config_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py similarity index 95% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_config_operation_status_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py index 950ba3486c8..85ba1ec79b0 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_config_operation_status_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py @@ -29,7 +29,7 @@ class FluxConfigOperationStatusOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -61,10 +61,10 @@ def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. @@ -73,7 +73,7 @@ def get( :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatusResult, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.OperationStatusResult + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.OperationStatusResult :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusResult"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py similarity index 97% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py index 016272f00de..a90ae89f0ea 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_flux_configurations_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py @@ -32,7 +32,7 @@ class FluxConfigurationsOperations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -63,17 +63,17 @@ def get( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. :type flux_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: FluxConfiguration, or the result of cls(response) - :rtype: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :rtype: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfiguration"] @@ -199,16 +199,16 @@ def begin_create_or_update( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. :type flux_configuration_name: str :param flux_configuration: Properties necessary to Create a FluxConfiguration. - :type flux_configuration: ~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration + :type flux_configuration: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. @@ -216,7 +216,7 @@ def begin_create_or_update( :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either FluxConfiguration or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.kubernetesconfiguration.models.FluxConfiguration] + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfiguration] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] @@ -344,10 +344,10 @@ def begin_delete( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :param flux_configuration_name: Name of the Flux Configuration. @@ -429,15 +429,15 @@ def list( :type resource_group_name: str :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). - :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.models.Enum0 + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). - :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.models.Enum1 + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 :param cluster_name: The name of the kubernetes cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either FluxConfigurationsList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.FluxConfigurationsList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.FluxConfigurationsList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.FluxConfigurationsList"] diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py new file mode 100644 index 00000000000..3f89f40a7d3 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py @@ -0,0 +1,132 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class OperationStatusOperations(object): + """OperationStatusOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + resource_group_name, # type: str + cluster_rp, # type: Union[str, "_models.Enum0"] + cluster_resource_name, # type: Union[str, "_models.Enum1"] + cluster_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.OperationStatusList"] + """List Async Operations, currently in progress, in a cluster. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + :type resource_group_name: str + :param cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS + clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + :type cluster_rp: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum0 + :param cluster_resource_name: The Kubernetes cluster resource name - either managedClusters + (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + :type cluster_resource_name: str or ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.Enum1 + :param cluster_name: The name of the kubernetes cluster. + :type cluster_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either OperationStatusList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.OperationStatusList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatusList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2021-06-01-preview" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), + 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), + 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), + 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), + 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('OperationStatusList', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operations.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operations.py similarity index 96% rename from src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operations.py rename to src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operations.py index 3e2bdacb973..7d7b898856a 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/operations/_operations.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operations.py @@ -30,7 +30,7 @@ class Operations(object): instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.kubernetesconfiguration.models + :type models: ~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. @@ -54,7 +54,7 @@ def list( :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ResourceProviderOperationList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationList] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.kubernetesconfiguration.v2021_06_01_preview.models.ResourceProviderOperationList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceProviderOperationList"] From 7d08c3ba8b38c6386d563ecbdcb2a3123c004352 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 11 Jun 2021 17:25:33 -0700 Subject: [PATCH 11/61] Support other extension methods --- src/k8s-config/azext_k8s_config/commands.py | 3 ++ src/k8s-config/azext_k8s_config/custom.py | 22 +++++++++++-- .../providers/ExtensionProvider.py | 31 +++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index d66ee32e851..49f5799a02e 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -31,3 +31,6 @@ def load_command_table(self, _): with self.command_group('k8s-config extension', k8s_config_extension_client, client_factory=k8s_config_extension_client, is_preview=True) as g: g.custom_command('create', 'extension_create') + g.custom_command('list', "extension_list") + g.custom_command('show', 'extension_show') + g.custom_command('delete', 'extension_delete', confirmation=True) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 74f98069a46..aca78c401f3 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -14,10 +14,9 @@ FluxConfiguration ) -def flux_config_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): - """Get an existing Kubernetes Source Control Configuration. +# Flux Configuration Methods - """ +def flux_config_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) return provider.show() @@ -41,6 +40,18 @@ def flux_config_delete(cmd, client, resource_group_name, cluster_name, cluster_t return provider.delete() +# Extension Methods + +def extension_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): + provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) + return provider.show() + + +def extension_list(cmd, client, resource_group_name, cluster_name, cluster_type): + provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type) + return provider.list() + + def extension_create(cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, version=None, target_namespace=None, release_namespace=None, configuration_settings=None, @@ -51,6 +62,11 @@ def extension_create(cmd, client, resource_group_name, cluster_name, name, clust configuration_settings, configuration_protected_settings, configuration_settings_file, configuration_protected_settings_file) +def extension_delete(cmd, client, resource_group_name, cluster_name, cluster_type, name): + provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) + return provider.delete() + + def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index d521f4de23f..96bc2dddfc0 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -50,6 +50,37 @@ def __init__(self, cmd, client, resource_group_name, cluster_name, cluster_type, self.name = name self.cluster_rp = get_cluster_rp(cluster_type) + + def show(self): + # Determine ClusterRP + try: + extension = self.client.get(self.resource_group_name, + self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + return extension + except CloudError as ex: + # Customize the error message for resources not found + if ex.response.status_code == 404: + # If Cluster not found + if ex.message.__contains__("(ResourceNotFound)"): + message = "{0} Verify that the cluster-type is correct and the resource exists.".format( + ex.message) + # If Configuration not found + elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): + message = "(ExtensionNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/" \ + "extensions/{3} could not be found!".format( + self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + else: + message = ex.message + raise ResourceNotFoundError(message) + + + def list(self): + return self.client.list(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name) + + + def delete(self): + return self.client.delete(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + def create(self, extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, version=None, target_namespace=None, release_namespace=None, configuration_settings=None, From 447ab1e6b558350c35adc0bb8c3103e653ca2001 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 22 Jun 2021 18:23:45 -0700 Subject: [PATCH 12/61] Fix nullity check --- src/k8s-config/azext_k8s_config/utils.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 5e9db364106..4aa48701d63 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -21,14 +21,14 @@ def get_cluster_rp(cluster_type): def get_data_from_key_or_file(key, filepath): - if key != '' and filepath != '': + if key and filepath: raise MutuallyExclusiveArgumentError( consts.KEY_AND_FILE_TOGETHER_ERROR, consts.KEY_AND_FILE_TOGETHER_HELP) data = '' - if filepath != '': + if filepath: data = read_key_file(filepath) - elif key != '': + elif key: data = key return data @@ -39,18 +39,18 @@ def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, ht # Add gitops private key data to protected settings if exists # Dry-run all key types to determine if the private key is in a valid format - if ssh_private_key_data != '': + if ssh_private_key_data: protected_settings[consts.SSH_PRIVATE_KEY_KEY] = ssh_private_key_data # Check if both httpsUser and httpsKey exist, then add to protected settings - if https_user != '' and https_key != '': + if https_user and https_key: protected_settings[consts.HTTPS_USER_KEY] = to_base64(https_user) protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key) - elif https_user != '': + elif https_user: raise RequiredArgumentMissingError( consts.HTTPS_USER_WITHOUT_KEY_ERROR, consts.HTTPS_USER_WITHOUT_KEY_HELP) - elif https_key != '': + elif https_key: raise RequiredArgumentMissingError( consts.HTTPS_KEY_WITHOUT_USER_ERROR, consts.HTTPS_KEY_WITHOUT_USER_HELP) From a38bef0e1464a0d7e4cffd959b0e4ec014071edc Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 24 Jun 2021 10:25:21 -0700 Subject: [PATCH 13/61] Add source control provider --- src/k8s-config/azext_k8s_config/custom.py | 44 ++++++------- .../providers/ExtensionProvider.py | 59 ++++++++--------- .../providers/FluxConfigurationProvider.py | 64 +++++++++---------- .../SourceControlConfigurationProvider.py | 52 +++++++++++++++ 4 files changed, 135 insertions(+), 84 deletions(-) create mode 100644 src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index aca78c401f3..c91e209b386 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -16,58 +16,58 @@ # Flux Configuration Methods -def flux_config_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): - provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) - return provider.show() +def flux_config_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = FluxConfigurationProvider(cmd) + return provider.show(resource_group_name, cluster_type, cluster_name, name) # pylint: disable=too-many-locals -def flux_config_create(cmd, client, resource_group_name, cluster_name, name, cluster_type, url=None, +def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): - provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) - return provider.create(url, scope, namespace, kind, timeout, sync_interval, + provider = FluxConfigurationProvider(cmd) + return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, branch, tag, semver, commit, auth_ref_override, ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, kustomization) -def flux_config_delete(cmd, client, resource_group_name, cluster_name, cluster_type, name): - provider = FluxConfigurationProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) - return provider.delete() +def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = FluxConfigurationProvider(cmd) + return provider.delete(resource_group_name, cluster_type, cluster_name, name) # Extension Methods -def extension_show(cmd, client, resource_group_name, cluster_name, cluster_type, name): - provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) - return provider.show() +def extension_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = ExtensionProvider(cmd) + return provider.show(resource_group_name, cluster_type, cluster_name, name) -def extension_list(cmd, client, resource_group_name, cluster_name, cluster_type): - provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type) - return provider.list() +def extension_list(cmd, client, resource_group_name, cluster_type, cluster_name): + provider = ExtensionProvider(cmd) + return provider.list(resource_group_name, cluster_type, cluster_name) -def extension_create(cmd, client, resource_group_name, cluster_name, name, cluster_type, +def extension_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, version=None, target_namespace=None, release_namespace=None, configuration_settings=None, configuration_protected_settings=None, configuration_settings_file=None, configuration_protected_settings_file=None, tags=None): - provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) - return provider.create(extension_type, scope, auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, + provider = ExtensionProvider(cmd) + return provider.create(resource_group_name, cluster_type, cluster_name, name, extension_type, scope, auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, configuration_settings, configuration_protected_settings, configuration_settings_file, configuration_protected_settings_file) -def extension_delete(cmd, client, resource_group_name, cluster_name, cluster_type, name): - provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type, name) - return provider.delete() +def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = ExtensionProvider(cmd) + return provider.delete(resource_group_name, cluster_type, cluster_name, name) -def flux_create_source(cmd, client, resource_group_name, cluster_name, name, cluster_type, url, +def flux_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url, scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, ssh_known_hosts=None, ssh_known_hosts_file=None): diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index 96bc2dddfc0..6359f1a5e3e 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -7,7 +7,7 @@ from knack.log import get_logger -from msrestazure.azure_exceptions import CloudError +from azure.core.exceptions import HttpResponseError from azure.cli.core.azclierror import ResourceNotFoundError, MutuallyExclusiveArgumentError, \ InvalidArgumentValueError, CommandNotFoundError, RequiredArgumentMissingError @@ -23,6 +23,7 @@ from ..utils import get_cluster_rp, read_config_settings_file from .._client_factory import cf_resources +from .._client_factory import k8s_config_extension_client logger = get_logger(__name__) @@ -41,23 +42,19 @@ def ExtensionFactory(extension_name): class ExtensionProvider: - def __init__(self, cmd, client, resource_group_name, cluster_name, cluster_type, name=None): + def __init__(self, cmd): self.cmd = cmd - self.client = client - self.resource_group_name = resource_group_name - self.cluster_name = cluster_name - self.cluster_type = cluster_type - self.name = name - self.cluster_rp = get_cluster_rp(cluster_type) + self.client = k8s_config_extension_client(cmd.cli_ctx) - def show(self): + def show(self, resource_group_name, cluster_type, cluster_name, name): # Determine ClusterRP + cluster_rp = get_cluster_rp(cluster_type) try: - extension = self.client.get(self.resource_group_name, - self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + extension = self.client.get(resource_group_name, + cluster_rp, cluster_type, cluster_name, name) return extension - except CloudError as ex: + except HttpResponseError as ex: # Customize the error message for resources not found if ex.response.status_code == 404: # If Cluster not found @@ -68,27 +65,31 @@ def show(self): elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): message = "(ExtensionNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/" \ "extensions/{3} could not be found!".format( - self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + cluster_rp, cluster_type, cluster_name, name) else: message = ex.message raise ResourceNotFoundError(message) - def list(self): - return self.client.list(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name) + def list(self, resource_group_name, cluster_type, cluster_name): + cluster_rp = get_cluster_rp(cluster_type) + return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - def delete(self): - return self.client.delete(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + def delete(self, resource_group_name, cluster_type, cluster_name, name): + cluster_rp = get_cluster_rp(cluster_type) + return self.client.delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) - def create(self, extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, + def create(self, resource_group_name, cluster_type, cluster_name, name, + extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, version=None, target_namespace=None, release_namespace=None, configuration_settings=None, configuration_protected_settings=None, configuration_settings_file=None, configuration_protected_settings_file=None, tags=None): """Create a new Extension Instance. """ + cluster_rp = get_cluster_rp(cluster_type) extension_type_lower = extension_type.lower() # Configuration Settings & Configuration Protected Settings @@ -135,7 +136,7 @@ def create(self, extension_type, scope=None, auto_upgrade_minor_version=None, re # Get the extension class based on the extension name extension_class = ExtensionFactory(extension_type_lower) extension_instance, name, create_identity = extension_class.Create( - self.cmd, self.client, self.resource_group_name, self.cluster_name, self.name, self.cluster_type, extension_type_lower, scope, + self.cmd, self.client, resource_group_name, cluster_name, name, cluster_type, extension_type_lower, scope, auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, config_settings, config_protected_settings, configuration_settings_file, configuration_protected_settings_file) @@ -148,7 +149,7 @@ def create(self, extension_type, scope=None, auto_upgrade_minor_version=None, re extension_instance.identity, extension_instance.location = self.__create_identity() # Try to create the resource - return self.client.create(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name, name, extension_instance) + return self.client.create(resource_group_name, cluster_rp, cluster_type, cluster_name, name, extension_instance) def __validate_scope_and_namespace(self, scope, release_namespace, target_namespace): if scope == 'cluster': @@ -176,25 +177,25 @@ def __validate_version_and_auto_upgrade(self, version, auto_upgrade_minor_versio auto_upgrade_minor_version = False - def __create_identity(self): + def __create_identity(self, resource_group_name, cluster_rp, cluster_type, cluster_name): subscription_id = get_subscription_id(self.cmd.cli_ctx) resources = cf_resources(self.cmd.cli_ctx, subscription_id) cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}'.format(subscription_id, - self.resource_group_name, - self.cluster_rp, - self.cluster_type, - self.cluster_name) + resource_group_name, + cluster_rp, + cluster_type, + cluster_name) - if self.cluster_rp == 'Microsoft.Kubernetes': + if cluster_rp == 'Microsoft.Kubernetes': parent_api_version = '2020-01-01-preview' - elif self.cluster_rp == 'Microsoft.ResourceConnector': + elif cluster_rp == 'Microsoft.ResourceConnector': parent_api_version = '2020-09-15-privatepreview' - elif self.cluster_rp == 'Microsoft.ContainerService': + elif cluster_rp == 'Microsoft.ContainerService': parent_api_version = '2017-07-01' else: raise InvalidArgumentValueError( - "Error! Cluster type '{}' is not supported for extension identity".format(self.cluster_type) + "Error! Cluster type '{}' is not supported for extension identity".format(cluster_type) ) try: diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index a46a46c78d4..428ac28fd3a 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -5,10 +5,9 @@ from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.core.exceptions import HttpResponseError -from .._client_factory import ( - k8s_config_sourcecontrol_client, - k8s_config_extension_client -) +from knack.log import get_logger + +from .._client_factory import k8s_config_fluxconfig_client from ..utils import get_cluster_rp, get_data_from_key_or_file, get_protected_settings from ..validators import ( validate_cc_registration, @@ -27,27 +26,26 @@ RepositoryRefDefinition, ) from .ExtensionProvider import ExtensionProvider +from .SourceControlConfigurationProvider import SourceControlConfigurationProvider +logger = get_logger(__name__) class FluxConfigurationProvider: - def __init__(self, cmd, client, resource_group_name, cluster_name, cluster_type, name=None): - self.extension_provider = ExtensionProvider(cmd, client, resource_group_name, cluster_name, cluster_type) + def __init__(self, cmd): + self.extension_provider = ExtensionProvider(cmd) + self.source_control_configuration_provider = SourceControlConfigurationProvider(cmd) self.cmd = cmd - self.client = client - self.resource_group_name = resource_group_name - self.cluster_name = cluster_name - self.cluster_type = cluster_type - self.name = name - self.cluster_rp = get_cluster_rp(cluster_type) + self.client = k8s_config_fluxconfig_client(cmd.cli_ctx) - def show(self): + def show(self, resource_group_name, cluster_type, cluster_name, name): """Get an existing Kubernetes Source Control Configuration. """ # Determine ClusterRP + cluster_rp = get_cluster_rp(cluster_type) try: - config = self.client.get(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name) return config except HttpResponseError as ex: # Customize the error message for resources not found @@ -56,15 +54,15 @@ def show(self): if ex.message.__contains__("(ResourceNotFound)"): message = ex.message recommendation = 'Verify that the --cluster-type is correct and the Resource ' \ - '{0}/{1}/{2} exists'.format(self.cluster_rp, self.cluster_type, self.cluster_name) + '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name) # If Configuration not found elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): - message = '(ConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \ - 'fluxConfigurations/{3} could not be found!'.format(self.cluster_rp, self.cluster_type, - self.cluster_name, self.name) + message = '(FluxConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \ + 'fluxConfigurations/{3} could not be found!'.format(cluster_rp, cluster_type, + cluster_name, name) recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \ - '/fluxConfigurations/{3} exists'.format(self.cluster_rp, self.cluster_type, - self.cluster_name, self.name) + '/fluxConfigurations/{3} exists'.format(cluster_rp, cluster_type, + cluster_name, name) else: message = ex.message recommendation = '' @@ -72,10 +70,12 @@ def show(self): # pylint: disable=too-many-locals - def create(self, url=None, scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, - branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, - ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + def create(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', + kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, + ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): + # Determine the cluster RP + cluster_rp = get_cluster_rp(cluster_type) # Pre-Validation validate_repository_ref(branch, tag, semver, commit) @@ -86,25 +86,23 @@ def create(self, url=None, scope='cluster', namespace='default', kind=consts.GIT validate_kustomization_list(kustomization) # Validate if we are able to install the flux configuration - scc_client = k8s_config_sourcecontrol_client(self.cmd.cli_ctx) - configs = scc_client.list(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name) + configs = self.source_control_configuration_provider.list(resource_group_name, cluster_type, cluster_name) # configs is an iterable, no len() so we have to iterate to check for configs for _ in configs: raise DeploymentError( consts.SCC_EXISTS_ON_CLUSTER_ERROR, consts.SCC_EXISTS_ON_CLUSTER_HELP) - # Validate if the extension is installed, if not, install it - extension_client = k8s_config_extension_client(self.cmd.cli_ctx) - extensions = extension_client.list(self.resource_group_name, self.cluster_rp, self.cluster_type, self.cluster_name) + # Validate if the extension is installed, if not, install it + extensions = self.extension_provider.list(resource_group_name, cluster_type, cluster_name) found_flux_extension = False for extension in extensions: if extension.extension_type.lower() == consts.FLUX_EXTENSION_TYPE: found_flux_extension = True break if not found_flux_extension: - self.extension_provider.create(self.cmd, self.client, self.resource_group_name, self.cluster_name, self.name, self.cluster_type, - consts.FLUX_EXTENSION_TYPE, "cluster") + logger.warning("'Micrsoft.Flux' extension not found on the cluster, installing it now. This may take a minute...") + self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE, release_train="preview") # Get the protected settings and validate the private key value protected_settings = get_protected_settings( @@ -154,10 +152,10 @@ def create(self, url=None, scope='cluster', namespace='default', kind=consts.GIT kustomizations=kustomization ) - return self.client.begin_create_or_update(self.resource_group_name, self.cluster_rp, - self.cluster_type, self.cluster_name, self.name, flux_configuration) + return self.client.begin_create_or_update(resource_group_name, cluster_rp, + cluster_type, cluster_name, name, flux_configuration) - def delete(self, client, resource_group_name, cluster_name, cluster_type, name): + def delete(self, client, resource_group_name, cluster_type, cluster_name, name): cluster_rp = get_cluster_rp(cluster_type) return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py new file mode 100644 index 00000000000..ce4f77d73cb --- /dev/null +++ b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py @@ -0,0 +1,52 @@ +from azure.cli.core.azclierror import ResourceNotFoundError +from azure.core.exceptions import HttpResponseError +from knack.log import get_logger + +from .._client_factory import k8s_config_sourcecontrol_client +from ..utils import get_cluster_rp + +logger = get_logger(__name__) + + +class SourceControlConfigurationProvider: + def __init__(self, cmd): + self.cmd = cmd + self.client = k8s_config_sourcecontrol_client(cmd.cli_ctx) + + + def show(self, resource_group_name, cluster_type, cluster_name, name): + # Determine ClusterRP + cluster_rp = get_cluster_rp(cluster_type) + try: + extension = self.client.get(resource_group_name, + cluster_rp, cluster_type, cluster_name, name) + return extension + except HttpResponseError as ex: + # Customize the error message for resources not found + if ex.response.status_code == 404: + # If Cluster not found + if ex.message.__contains__("(ResourceNotFound)"): + message = "{0} Verify that the cluster-type is correct and the resource exists.".format( + ex.message) + # If Configuration not found + elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): + message = "(SourceControlConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/" \ + "sourceControlConfigurations/{3} could not be found!".format( + self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + else: + message = ex.message + raise ResourceNotFoundError(message) + + + def list(self, resource_group_name, cluster_type, cluster_name): + cluster_rp = get_cluster_rp(cluster_type) + return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) + + + def delete(self, resource_group_name, cluster_type, cluster_name, name): + cluster_rp = get_cluster_rp(cluster_type) + return self.client.delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + + + def create(): + pass \ No newline at end of file From 87370ecdefb4458d048d04ec7dfab0cce1ce304e Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 28 Jun 2021 14:42:04 -0700 Subject: [PATCH 14/61] Add scc commands --- src/k8s-config/azext_k8s_config/commands.py | 16 ++++++++++++++-- src/k8s-config/azext_k8s_config/custom.py | 3 ++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 49f5799a02e..40928a6dcff 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -7,7 +7,8 @@ from azure.cli.core.commands import CliCommandType from azext_k8s_config._client_factory import ( k8s_config_fluxconfig_client, - k8s_config_extension_client + k8s_config_extension_client, + k8s_config_sourcecontrol_client ) @@ -22,6 +23,11 @@ def load_command_table(self, _): client_factory=k8s_config_extension_client ) + k8s_config_sourcecontrol_sdk = CliCommandType( + operations_tmpl='azext_k8s_config.vendored_sdks.operations#SourceControlConfigurationsOperations.{}', + client_factory=k8s_config_sourcecontrol_client + ) + with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_preview=True) as g: g.custom_command('create', 'flux_config_create') g.command('list', "list") @@ -29,8 +35,14 @@ def load_command_table(self, _): g.custom_command('delete', 'flux_config_delete', confirmation=True) g.custom_command('source create', 'flux_create_source', supports_local_cache=True) - with self.command_group('k8s-config extension', k8s_config_extension_client, client_factory=k8s_config_extension_client, is_preview=True) as g: + with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: g.custom_command('create', 'extension_create') g.custom_command('list', "extension_list") g.custom_command('show', 'extension_show') g.custom_command('delete', 'extension_delete', confirmation=True) + + with self.command_group('k8s-config source', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client) as g: + g.custom_command('create', 'source_create') + g.custom_command('list', 'list_k8sconfiguration') + g.custom_show_command('show', 'show_k8sconfiguration') + g.custom_command('delete', 'delete_k8sconfiguration', confirmation=True) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index c91e209b386..98eb94ce443 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -101,7 +101,8 @@ def flux_create_source(cmd, client, resource_group_name, cluster_type, cluster_n kustomizations=[] ) # cache the payload if --defer used or send to Azure - return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, cluster_rp, cluster_type, cluster_name, name) + return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, name) + # return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, cluster_rp, cluster_type, cluster_name, name) # def flux_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, # dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): From d9e8bf055d0ab64c5ccc732328b323bd53df0b23 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 30 Jun 2021 12:55:20 -0700 Subject: [PATCH 15/61] Add defer logic for create with cache --- src/k8s-config/azext_k8s_config/_params.py | 157 +++++++-------- src/k8s-config/azext_k8s_config/action.py | 6 +- src/k8s-config/azext_k8s_config/commands.py | 3 +- src/k8s-config/azext_k8s_config/consts.py | 5 +- src/k8s-config/azext_k8s_config/custom.py | 61 ++---- .../providers/FluxConfigurationProvider.py | 181 +++++++++++++----- src/k8s-config/azext_k8s_config/utils.py | 15 ++ src/k8s-config/azext_k8s_config/validators.py | 15 +- 8 files changed, 273 insertions(+), 170 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 7bffc25fdcd..c3878efbe99 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -68,6 +68,9 @@ def load_arguments(self, _): c.argument('commit', arg_group="Repo Ref", help='Specific commit to reconcile with the git source') + c.argument('branch_commit', + arg_group="Repo Ref", + help="Specific commit and branch to reconcile with the git source") c.argument('ssh_private_key', arg_group="Auth", help='Base64-encoded private ssh key for private repository sync') @@ -86,8 +89,8 @@ def load_arguments(self, _): c.argument('known_hosts_file', arg_group="Auth", help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') - c.argument('auth_ref_override', - options_list=['--auth-ref-override'], + c.argument('local_auth_ref', + options_list=['--local-auth-ref'], arg_group="Auth", help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') c.argument('kustomization', @@ -138,78 +141,80 @@ def load_arguments(self, _): help='Specify the target namespace to install to for the extension instance. This' ' parameter is required if extension scope is set to \'namespace\'') - # with self.argument_context('k8s-config flux source') as c: - # c.argument('scope', - # arg_type=get_enum_type(['namespace', 'cluster']), - # help="Specify scope of the operator to be 'namespace' or 'cluster'") - # c.argument('namespace', - # help='Specify namespace to deploy the configuration', - # validator=validate_namespace) - # c.argument('kind', - # arg_type=get_enum_type(['git']), - # options_list=['--kind', '-k'], - # help='Specify the source kind to reconcile') - # c.argument('url', - # help='Specify namespace to deploy the configuration') - # c.argument('timeout', - # help='Specify the source kind to reconcile') - # c.argument('sync_interval', - # options_list=['--interval', '--sync-interval'], - # help='Specify the source kind to reconcile') - # c.argument('branch', - # arg_group="Repo Ref", - # help='Specify the branch to reconcile the git repository source kind') - # c.argument('tag', - # arg_group="Repo Ref", - # help='Specify the branch to reconcile the git repository source kind') - # c.argument('semver', - # arg_group="Repo Ref", - # help='Specify the branch to reconcile the git repository source kind') - # c.argument('commit', - # arg_group="Repo Ref", - # help='Specify the branch to reconcile the git repository source kind') - # c.argument('auth_ref_override', - # options_list=['--auth-ref-override', '--auth-ref'], - # help='Specify the branch to reconcile the git repository source kind') - # c.argument('ssh_private_key', - # arg_group="Auth", - # help='Specify Base64-encoded private ssh key for private repository sync') - # c.argument('ssh_private_key_file', - # arg_group="Auth", - # help='Specify filepath to private ssh key for private repository sync') - # c.argument('https_user', - # arg_group="Auth", - # help='Specify HTTPS username for private repository sync') - # c.argument('https_key', - # arg_group="Auth", - # help='Specify HTTPS token/password for private repository sync') - # c.argument('ssh_known_hosts', - # arg_group="Auth", - # help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') - # c.argument('ssh_known_hosts_file', - # arg_group="Auth", - # help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') + with self.argument_context('k8s-config flux source') as c: + c.argument('scope', + options_list=['--scope', '-s'], + arg_type=get_enum_type(['namespace', 'cluster']), + help="Specify scope of the operator to be 'namespace' or 'cluster'") + c.argument('namespace', + help='Namespace to deploy the configuration', + options_list=['--namespace', '--ns'], + validator=validate_namespace) + c.argument('kind', + arg_type=get_enum_type([consts.GIT]), + help='Source kind to reconcile') + c.argument('url', + options_list=['--url', '-u'], + help='URL of the source to reconcile') + c.argument('timeout', + help='Maximum time to reconcile the source before timing out') + c.argument('sync_interval', + options_list=['--interval', '--sync-interval'], + help='Time between reconciliations of the source on the cluster') + c.argument('branch', + arg_group="Repo Ref", + help='Branch to reconcile with the git source') + c.argument('tag', + arg_group="Repo Ref", + help='Tag to reconcile with the git source') + c.argument('semver', + arg_group="Repo Ref", + help='Semver range to reconcile with the git source') + c.argument('commit', + arg_group="Repo Ref", + help='Specific commit to reconcile with the git source') + c.argument('ssh_private_key', + arg_group="Auth", + help='Base64-encoded private ssh key for private repository sync') + c.argument('ssh_private_key_file', + arg_group="Auth", + help='Filepath to private ssh key for private repository sync') + c.argument('https_user', + arg_group="Auth", + help='HTTPS username for private repository sync') + c.argument('https_key', + arg_group="Auth", + help='HTTPS token/password for private repository sync') + c.argument('known_hosts', + arg_group="Auth", + help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') + c.argument('known_hosts_file', + arg_group="Auth", + help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') + c.argument('local_auth_ref', + options_list=['--local-auth-ref'], + arg_group="Auth", + help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') - # with self.argument_context('k8s-config flux kustomization') as c: - # c.argument('config_name', - # help='Specify the name of the configuration to create the kustomization', - # validator=validate_namespace) - # c.argument('path', - # help='Specify the name of the configuration to create the kustomization') - # c.argument('dependencies', - # options_list=['--depends', '--dependencies'], - # help='Specify the name of the configuration to create the kustomization') - # c.argument('timeout', - # help='Specify the source kind to reconcile') - # c.argument('sync_interval', - # options_list=['--interval', '--sync-interval'], - # help='Specify the source kind to reconcile') - # c.argument('retry_interval', - # help='Specify the source kind to reconcile') - # c.argument('prune', - # help='Specify the source kind to reconcile') - # c.argument('force', - # help='Specify the source kind to reconcile') - # c.argument('validation', - # arg_type=get_enum_type(['none', 'client', 'server']), - # help='Specify the source kind to reconcile') + with self.argument_context('k8s-config flux kustomization') as c: + c.argument('config_name', + help='Specify the name of the configuration to create the kustomization') + c.argument('path', + help='Specify the name of the configuration to create the kustomization') + c.argument('dependencies', + options_list=['--depends', '--dependencies'], + help='Specify the name of the configuration to create the kustomization') + c.argument('timeout', + help='Specify the source kind to reconcile') + c.argument('sync_interval', + options_list=['--interval', '--sync-interval'], + help='Specify the source kind to reconcile') + c.argument('retry_interval', + help='Specify the source kind to reconcile') + c.argument('prune', + help='Specify the source kind to reconcile') + c.argument('force', + help='Specify the source kind to reconcile') + c.argument('validation', + arg_type=get_enum_type(['none', 'client', 'server']), + help='Specify the source kind to reconcile') diff --git a/src/k8s-config/azext_k8s_config/action.py b/src/k8s-config/azext_k8s_config/action.py index 99c4bc6d6a7..9b772b4f53e 100644 --- a/src/k8s-config/azext_k8s_config/action.py +++ b/src/k8s-config/azext_k8s_config/action.py @@ -9,14 +9,14 @@ from .vendored_sdks.v2021_06_01_preview.models import KustomizationDefinition from .validators import validate_kustomization from . import consts -from .utils import parse_dependencies +from .utils import parse_dependencies, get_duration class KustomizationAddAction(argparse._AppendAction): def __call__(self, parser, namespace, values, option_string=None): validate_kustomization(values) dependencies = [] - sync_interval = "" + sync_interval = None kwargs = {} for item in values: try: @@ -32,7 +32,7 @@ def __call__(self, parser, namespace, values, option_string=None): super(KustomizationAddAction, self).__call__( parser, namespace, - KustomizationDefinition(depends_on=dependencies, sync_interval=sync_interval, **kwargs), + KustomizationDefinition(depends_on=dependencies, sync_interval=get_duration(sync_interval), **kwargs), option_string ) diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 40928a6dcff..96f21fc4003 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -33,7 +33,8 @@ def load_command_table(self, _): g.command('list', "list") g.custom_command('show', 'flux_config_show') g.custom_command('delete', 'flux_config_delete', confirmation=True) - g.custom_command('source create', 'flux_create_source', supports_local_cache=True) + g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) + g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: g.custom_command('create', 'extension_create') diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index e288ff12cd4..cbebaa284fe 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -19,6 +19,9 @@ REPOSITORY_REF_REQUIRED_VALUES_MISSING_ERROR = "Error! Repository reference is invalid" REPOSITORY_REF_REQUIRED_VALUES_MISSING_HELP = "Specifying one of [--branch, --tag, --semver, --commit] is required" +REPOSITORY_REF_TOO_MAY_VALUES_ERROR = "Error! Repository reference is invalid" +REPOSITORY_REF_TOO_MAY_VALUES_HELP = "Specifying more than one repository ref argument that isn't --branch and --commit is invalid" + GIT_REPOSITORY_REQUIRED_VALUES_MISSING_ERROR = "Error! Git repository kind is missing required value {}" GIT_REPOSITORY_REQUIRED_VALUES_MISSING_HELP = "Add missing git repository kind and try again" @@ -94,7 +97,7 @@ TIMEOUT_KEY = "timeout" REQUIRED_KUSTOMIZATION_KEYS = {"name", "path"} -VALID_ISO8601_DURATION_REGEX = r"^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$" +VALID_DURATION_REGEX = r"((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?" VALID_URL_REGEX = r"^(((http|https|ssh)://)|(git@))" VALID_KUBERNETES_NAME_REGEX = r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 98eb94ce443..fded21b0315 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -24,17 +24,36 @@ def flux_config_show(cmd, client, resource_group_name, cluster_type, cluster_nam # pylint: disable=too-many-locals def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, - branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, ssh_private_key=None, + branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): provider = FluxConfigurationProvider(cmd) return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, - branch, tag, semver, commit, auth_ref_override, ssh_private_key, + branch, tag, semver, commit, local_auth_ref, ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, kustomization) +def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, + scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, + branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, + ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + known_hosts_file=None): + + provider = FluxConfigurationProvider(cmd) + return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, + branch, tag, semver, commit, local_auth_ref, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, + known_hosts_file) + +def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, + dependencies=None, timeout=None, sync_interval=None, retry_interval=None, path='', prune=False, validation='none', force=False): + + provider = FluxConfigurationProvider(cmd) + return provider.create_kustomization(resource_group_name, cluster_name, config_name, name, cluster_type, + dependencies, timeout, sync_interval, retry_interval, path, prune, validation, force) + def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): provider = FluxConfigurationProvider(cmd) return provider.delete(resource_group_name, cluster_type, cluster_name, name) @@ -66,44 +85,6 @@ def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_nam provider = ExtensionProvider(cmd) return provider.delete(resource_group_name, cluster_type, cluster_name, name) - -def flux_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url, - scope='cluster', namespace='default', kind='git', timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, - auth_ref_override=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, - ssh_known_hosts=None, ssh_known_hosts_file=None): - from azure.cli.core.commands import cached_get, cached_put - - # Determine ClusterRP - cluster_rp = get_cluster_rp(cluster_type) - - repository_ref = RepositoryRefDefinition( - branch=branch, - tag=tag, - semver=semver, - commit=commit - ) - - git_repository = GitRepositoryDefinition( - url=url, - timeout=timeout, - sync_interval=sync_interval, - repository_ref=repository_ref, - ssh_known_hosts=ssh_known_hosts, - https_user=https_user, - auth_ref_override=auth_ref_override - ) - - flux_configuration = FluxConfiguration( - scope=scope, - namespace=namespace, - source_kind=kind, - git_repository=git_repository, - kustomizations=[] - ) - # cache the payload if --defer used or send to Azure - return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, name) - # return cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, cluster_rp, cluster_type, cluster_name, name) - # def flux_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, # dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 428ac28fd3a..0fe661b92c6 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -4,11 +4,12 @@ # -------------------------------------------------------------------------------------------- from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError +from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property from azure.core.exceptions import HttpResponseError from knack.log import get_logger from .._client_factory import k8s_config_fluxconfig_client -from ..utils import get_cluster_rp, get_data_from_key_or_file, get_protected_settings +from ..utils import get_cluster_rp, get_data_from_key_or_file, get_protected_settings, get_duration from ..validators import ( validate_cc_registration, validate_known_hosts, @@ -23,6 +24,7 @@ from ..vendored_sdks.v2021_06_01_preview.models import ( FluxConfiguration, GitRepositoryDefinition, + KustomizationDefinition, RepositoryRefDefinition, ) from .ExtensionProvider import ExtensionProvider @@ -71,28 +73,123 @@ def show(self, resource_group_name, cluster_type, cluster_name, name): # pylint: disable=too-many-locals def create(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', - kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, auth_ref_override=None, + kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): + # Determine the cluster RP cluster_rp = get_cluster_rp(cluster_type) + dp_source_kind = "" + git_repository = None - # Pre-Validation - validate_repository_ref(branch, tag, semver, commit) - validate_duration("--timeout", timeout) - validate_duration("--sync-interval", sync_interval) + self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + + if kind == consts.GIT: + dp_source_kind = consts.GIT_REPOSITORY + git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, + known_hosts_file, local_auth_ref) if kustomization: validate_kustomization_list(kustomization) - # Validate if we are able to install the flux configuration + flux_configuration = FluxConfiguration( + scope=scope, + namespace=namespace, + source_kind=dp_source_kind, + timeout=timeout, + sync_interval=sync_interval, + git_repository=git_repository, + kustomizations=kustomization + ) + + return self.client.begin_create_or_update(resource_group_name, cluster_rp, + cluster_type, cluster_name, name, flux_configuration) + + def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', + kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, + ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + known_hosts_file=None): + # Determine the cluster RP + cluster_rp = get_cluster_rp(cluster_type) + dp_source_kind = "" + git_repository = None + + # Validate the extension install if this is not a deferred command + if not self._is_deferred(): + self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + + if kind == consts.GIT: + dp_source_kind = consts.GIT_REPOSITORY + git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, + known_hosts_file, local_auth_ref) + + flux_configuration = FluxConfiguration( + scope=scope, + namespace=namespace, + source_kind=dp_source_kind, + git_repository=git_repository, + kustomizations=[] + ) + + # cache the payload if --defer used or send to Azure + return cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, + flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, + cluster_name=cluster_name, setter_arg_name='flux_configuration') + + def create_kustomization(self, resource_group_name, cluster_name, config_name, name, cluster_type, + dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): + # Determine ClusterRP + cluster_rp = get_cluster_rp(cluster_type) + + # Validate the extension install if this is not a deferred command + if not self._is_deferred(): + self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + + flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name, cluster_rp, cluster_type, cluster_name, config_name) + + kustomization = KustomizationDefinition( + name=name, + path=path, + dependencies=dependencies, + timeout_in_seconds=timeout, + sync_interval_in_seconds=sync_interval, + retry_interval_in_seconds=retry_interval, + prune=prune, + validation=validation, + force=force + ) + + proposed_change = flux_configuration.kustomizations[:] + kustomization + validate_kustomization_list(proposed_change) + + upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') + flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name, setter_arg_name='flux_configuration') + return get_property(flux_configuration.kustomizations, name) + + def delete(self, client, resource_group_name, cluster_type, cluster_name, name): + cluster_rp = get_cluster_rp(cluster_type) + return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + + def _is_deferred(self): + if '--defer' in self.cmd.cli_ctx.data.get('safe_params'): + return True + return False + + def _validate_source_control_config_not_installed(self, resource_group_name, cluster_type, cluster_name): + # Validate if we are able to install the flux configuration configs = self.source_control_configuration_provider.list(resource_group_name, cluster_type, cluster_name) # configs is an iterable, no len() so we have to iterate to check for configs for _ in configs: raise DeploymentError( consts.SCC_EXISTS_ON_CLUSTER_ERROR, consts.SCC_EXISTS_ON_CLUSTER_HELP) - + + def _validate_extension_install(self, resource_group_name, cluster_type, cluster_name): # Validate if the extension is installed, if not, install it extensions = self.extension_provider.list(resource_group_name, cluster_type, cluster_name) found_flux_extension = False @@ -104,6 +201,12 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None logger.warning("'Micrsoft.Flux' extension not found on the cluster, installing it now. This may take a minute...") self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE, release_train="preview") + def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, local_auth_ref): + # Pre-Validation + validate_duration("--timeout", timeout) + validate_duration("--sync-interval", sync_interval) + # Get the protected settings and validate the private key value protected_settings = get_protected_settings( ssh_private_key, ssh_private_key_file, https_user, https_key @@ -119,43 +222,29 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None # Validate registration with the RP endpoint validate_cc_registration(self.cmd) - git_repository = GitRepositoryDefinition() - dp_source_kind = consts.GIT_REPOSITORY - - if kind == consts.GIT: - validate_git_repository(url) - validate_url_with_params(url, ssh_private_key, ssh_private_key_file, - known_hosts, known_hosts_file, https_user, https_key) - repository_ref = RepositoryRefDefinition( - branch=branch, - tag=tag, - semver=semver, - commit=commit - ) - git_repository = GitRepositoryDefinition( - url=url, - timeout=timeout, - sync_interval=sync_interval, - repository_ref=repository_ref, - ssh_known_hosts=knownhost_data, - https_user=https_user, - auth_ref_override=auth_ref_override - ) - - flux_configuration = FluxConfiguration( - scope=scope, - namespace=namespace, - source_kind=dp_source_kind, - timeout=timeout, - sync_interval=sync_interval, - git_repository=git_repository, - kustomizations=kustomization + validate_git_repository(url) + validate_url_with_params(url, ssh_private_key, ssh_private_key_file, + known_hosts, known_hosts_file, https_user, https_key) + + repository_ref = self._validate_and_get_repository_ref(branch, tag, semver, commit) + + + return GitRepositoryDefinition( + url=url, + timeout_in_seconds=get_duration(timeout), + sync_interval_in_seconds=get_duration(sync_interval), + repository_ref=repository_ref, + ssh_known_hosts=knownhost_data, + https_user=https_user, + local_auth_ref=local_auth_ref ) + + def _validate_and_get_repository_ref(self, branch, tag, semver, commit): + validate_repository_ref(branch, tag, semver, commit) - return self.client.begin_create_or_update(resource_group_name, cluster_rp, - cluster_type, cluster_name, name, flux_configuration) - - - def delete(self, client, resource_group_name, cluster_type, cluster_name, name): - cluster_rp = get_cluster_rp(cluster_type) - return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) \ No newline at end of file + return RepositoryRefDefinition( + branch=branch, + tag=tag, + semver=semver, + commit=commit + ) diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 4aa48701d63..86add539b1c 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -5,6 +5,8 @@ import base64 import json +import re +from datetime import timedelta from azure.cli.core.azclierror import ( MutuallyExclusiveArgumentError, InvalidArgumentValueError, @@ -94,6 +96,19 @@ def parse_dependencies(depends_on): return depends_on.split(',') +def get_duration(duration): + if not duration: + return duration + regex = re.compile(r'((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?') + parts = regex.match(duration) + parts = parts.groupdict() + time_params = {} + for name, param in parts.items(): + if param: + time_params[name] = int(param) + return int(timedelta(**time_params).total_seconds()) + + def from_base64(base64_str): return base64.b64decode(base64_str) diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index 4c9730189f3..cde2a58734b 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -70,15 +70,25 @@ def validate_kustomization_list(kustomizations): def validate_repository_ref(branch: str, tag: str, semver: str, commit: str): - if not branch and not tag and not semver and not commit: + num_set_args = 0 + for elem in [branch, tag, semver, commit]: + if elem: + num_set_args += 1 + if num_set_args == 0: raise RequiredArgumentMissingError( consts.REPOSITORY_REF_REQUIRED_VALUES_MISSING_ERROR, consts.REPOSITORY_REF_REQUIRED_VALUES_MISSING_HELP ) + if num_set_args == 1 or (num_set_args == 2 and (branch and commit)): + return + raise MutuallyExclusiveArgumentError( + consts.REPOSITORY_REF_TOO_MAY_VALUES_ERROR, + consts.REPOSITORY_REF_TOO_MAY_VALUES_HELP + ) def validate_duration(arg_name: str, duration: str): - if duration and not re.match(consts.VALID_ISO8601_DURATION_REGEX, duration): + if duration and not re.match(consts.VALID_DURATION_REGEX, duration): raise InvalidArgumentValueError( consts.INVALID_DURATION_ERROR.format(arg_name), consts.INVALID_DURATION_HELP @@ -125,7 +135,6 @@ def validate_url_with_params(url: str, ssh_private_key, ssh_private_key_file, known_hosts, known_hosts_file, https_user, https_key): scheme = urlparse(url).scheme - if scheme.lower() in ('http', 'https'): if ssh_private_key or ssh_private_key_file: raise MutuallyExclusiveArgumentError( From b7a894efbb3cb5d93ba2d6d53afea0ace242b2b9 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 2 Jul 2021 12:00:56 -0700 Subject: [PATCH 16/61] Use default extension with identity --- .../{Cassandra.py => DefaultExtensionWithIdentity.py} | 2 +- .../azext_k8s_config/providers/ExtensionProvider.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) rename src/k8s-config/azext_k8s_config/partner_extensions/{Cassandra.py => DefaultExtensionWithIdentity.py} (97%) diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py similarity index 97% rename from src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py rename to src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py index e977cd2e77c..2e53a730c5f 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py @@ -15,7 +15,7 @@ from .PartnerExtensionModel import PartnerExtensionModel -class Cassandra(PartnerExtensionModel): +class DefaultExtensionWithIdentity(PartnerExtensionModel): def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, scope, auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, configuration_settings, configuration_protected_settings, diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index 6359f1a5e3e..b6ea0715cda 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -17,9 +17,10 @@ from ..partner_extensions.ContainerInsights import ContainerInsights from ..partner_extensions.AzureDefender import AzureDefender -from ..partner_extensions.Cassandra import Cassandra from ..partner_extensions.AzureMLKubernetes import AzureMLKubernetes from ..partner_extensions.DefaultExtension import DefaultExtension +from ..partner_extensions.DefaultExtensionWithIdentity import DefaultExtensionWithIdentity + from ..utils import get_cluster_rp, read_config_settings_file from .._client_factory import cf_resources @@ -34,7 +35,8 @@ def ExtensionFactory(extension_name): 'microsoft.azuremonitor.containers': ContainerInsights, 'microsoft.azuredefender.kubernetes': AzureDefender, 'microsoft.azureml.kubernetes': AzureMLKubernetes, - 'cassandradatacentersoperator': Cassandra, + 'microsoft.flux': DefaultExtensionWithIdentity, + 'cassandradatacentersoperator': DefaultExtensionWithIdentity, } # Return the extension if we find it in the map, else return the default From 9849c4eb35ca4734d163b718fc4e472dd193cfa1 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 2 Jul 2021 12:04:06 -0700 Subject: [PATCH 17/61] Fix identity creation --- src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index b6ea0715cda..d9689ac902f 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -148,7 +148,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, # Create identity, if required if create_identity: - extension_instance.identity, extension_instance.location = self.__create_identity() + extension_instance.identity, extension_instance.location = self.__create_identity(resource_group_name, cluster_rp, cluster_type, cluster_name) # Try to create the resource return self.client.create(resource_group_name, cluster_rp, cluster_type, cluster_name, name, extension_instance) From 62a2d88335a170959110f3964aea266354f7fb7b Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 6 Jul 2021 12:02:27 -0700 Subject: [PATCH 18/61] Add kustomization caching --- src/k8s-config/azext_k8s_config/_params.py | 20 +-- src/k8s-config/azext_k8s_config/commands.py | 10 +- src/k8s-config/azext_k8s_config/consts.py | 2 +- src/k8s-config/azext_k8s_config/custom.py | 33 +---- .../providers/ExtensionProvider.py | 6 +- .../providers/FluxConfigurationProvider.py | 122 +++++++++--------- 6 files changed, 82 insertions(+), 111 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index c3878efbe99..0a7b751130f 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -197,24 +197,24 @@ def load_arguments(self, _): help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') with self.argument_context('k8s-config flux kustomization') as c: - c.argument('config_name', - help='Specify the name of the configuration to create the kustomization') + c.argument('kustomization_name', + help='Specify the name of the kustomization to add to the configuration') c.argument('path', - help='Specify the name of the configuration to create the kustomization') + help='Specify the path in the source that the kustomization should apply') c.argument('dependencies', options_list=['--depends', '--dependencies'], - help='Specify the name of the configuration to create the kustomization') + help='Specify the names of kustomization dependencies') c.argument('timeout', - help='Specify the source kind to reconcile') + help='Maximum time to reconcile the kustomization before timing out') c.argument('sync_interval', options_list=['--interval', '--sync-interval'], - help='Specify the source kind to reconcile') + help='Time between reconciliations of the kustomization on the cluster') c.argument('retry_interval', - help='Specify the source kind to reconcile') + help='Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval') c.argument('prune', - help='Specify the source kind to reconcile') + help='Whether to garbage collect resources deployed by the kustomization on the cluster') c.argument('force', - help='Specify the source kind to reconcile') + help='Whether to re-create resources that cannot be updated on the cluster (i.e. jobs)') c.argument('validation', arg_type=get_enum_type(['none', 'client', 'server']), - help='Specify the source kind to reconcile') + help='Specify whether to dry-run manifests at the client or at the apiserver level before applying them to the cluster.') diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 96f21fc4003..6fb255f386f 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -42,8 +42,8 @@ def load_command_table(self, _): g.custom_command('show', 'extension_show') g.custom_command('delete', 'extension_delete', confirmation=True) - with self.command_group('k8s-config source', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client) as g: - g.custom_command('create', 'source_create') - g.custom_command('list', 'list_k8sconfiguration') - g.custom_show_command('show', 'show_k8sconfiguration') - g.custom_command('delete', 'delete_k8sconfiguration', confirmation=True) + # with self.command_group('k8s-config source', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client) as g: + # g.custom_command('create', 'source_create') + # g.custom_command('list', 'list_k8sconfiguration') + # g.custom_show_command('show', 'show_k8sconfiguration') + # g.custom_command('delete', 'delete_k8sconfiguration', confirmation=True) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index cbebaa284fe..ead2ddb3810 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -7,7 +7,7 @@ # API VERSIONS ----------------------------------------- -EXTENSION_API_VERSION = '2020-07-01-preview' +EXTENSION_API_VERSION = '2021-05-01-preview' SOURCE_CONTROL_API_VERSION = '2021-03-01' FLUXCONFIG_API_VERSION = '2021-06-01-preview' diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index fded21b0315..6bc9f47548e 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -8,11 +8,6 @@ from .utils import get_cluster_rp from . import consts -from .vendored_sdks.v2021_06_01_preview.models import ( - RepositoryRefDefinition, - GitRepositoryDefinition, - FluxConfiguration -) # Flux Configuration Methods @@ -47,11 +42,11 @@ def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cl ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file) -def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, +def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, kustomization_name, dependencies=None, timeout=None, sync_interval=None, retry_interval=None, path='', prune=False, validation='none', force=False): provider = FluxConfigurationProvider(cmd) - return provider.create_kustomization(resource_group_name, cluster_name, config_name, name, cluster_type, + return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, dependencies, timeout, sync_interval, retry_interval, path, prune, validation, force) def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): @@ -84,27 +79,3 @@ def extension_create(cmd, client, resource_group_name, cluster_type, cluster_nam def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): provider = ExtensionProvider(cmd) return provider.delete(resource_group_name, cluster_type, cluster_name, name) - -# def flux_create_kustomization(cmd, client, resource_group_name, cluster_name, config_name, name, cluster_type, -# dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): - -# # Determine ClusterRP -# cluster_rp = get_cluster_type(cluster_type) - -# flux_configuration = cached_get(cmd, client.get, resource_group_name, cluster_rp, cluster_type, cluster_name, config_name) - -# kustomization = KustomizationDefinition( -# name=name, -# path=path, -# dependencies=dependencies, -# timeout=timeout, -# sync_interval=sync_interval, -# retry_interval=retry_interval, -# prune=prune, -# validation=validation, -# force=force -# ) - -# upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') -# flux_configuration = cached_put(cmd, client.begin_create_or_update, flux_configuration, resource_group_name, name).result() -# return get_property(flux_configuration.kustomizations, name) diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index d9689ac902f..10da8a2d567 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -35,7 +35,7 @@ def ExtensionFactory(extension_name): 'microsoft.azuremonitor.containers': ContainerInsights, 'microsoft.azuredefender.kubernetes': AzureDefender, 'microsoft.azureml.kubernetes': AzureMLKubernetes, - 'microsoft.flux': DefaultExtensionWithIdentity, + 'microsoft.flux': DefaultExtension, 'cassandradatacentersoperator': DefaultExtensionWithIdentity, } @@ -80,7 +80,7 @@ def list(self, resource_group_name, cluster_type, cluster_name): def delete(self, resource_group_name, cluster_type, cluster_name, name): cluster_rp = get_cluster_rp(cluster_type) - return self.client.delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) def create(self, resource_group_name, cluster_type, cluster_name, name, @@ -151,7 +151,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, extension_instance.identity, extension_instance.location = self.__create_identity(resource_group_name, cluster_rp, cluster_type, cluster_name) # Try to create the resource - return self.client.create(resource_group_name, cluster_rp, cluster_type, cluster_name, name, extension_instance) + return self.client.begin_create(resource_group_name, cluster_rp, cluster_type, cluster_name, name, extension_instance) def __validate_scope_and_namespace(self, scope, release_namespace, target_namespace): if scope == 'cluster': diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 0fe661b92c6..5226bfa4b8c 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -107,69 +107,69 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None return self.client.begin_create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) - def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', - kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, - ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None): - # Determine the cluster RP - cluster_rp = get_cluster_rp(cluster_type) - dp_source_kind = "" - git_repository = None - - # Validate the extension install if this is not a deferred command - if not self._is_deferred(): - self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name) - - if kind == consts.GIT: - dp_source_kind = consts.GIT_REPOSITORY - git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, - known_hosts_file, local_auth_ref) + # def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', + # kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, + # ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + # known_hosts_file=None): + # # Determine the cluster RP + # cluster_rp = get_cluster_rp(cluster_type) + # dp_source_kind = "" + # git_repository = None + + # # Validate the extension install if this is not a deferred command + # if not self._is_deferred(): + # self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + # self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + + # if kind == consts.GIT: + # dp_source_kind = consts.GIT_REPOSITORY + # git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, + # ssh_private_key_file, https_user, https_key, known_hosts, + # known_hosts_file, local_auth_ref) - flux_configuration = FluxConfiguration( - scope=scope, - namespace=namespace, - source_kind=dp_source_kind, - git_repository=git_repository, - kustomizations=[] - ) - - # cache the payload if --defer used or send to Azure - return cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, - flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, - cluster_name=cluster_name, setter_arg_name='flux_configuration') - - def create_kustomization(self, resource_group_name, cluster_name, config_name, name, cluster_type, - dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): - # Determine ClusterRP - cluster_rp = get_cluster_rp(cluster_type) + # flux_configuration = FluxConfiguration( + # scope=scope, + # namespace=namespace, + # source_kind=dp_source_kind, + # git_repository=git_repository, + # kustomizations=[] + # ) + + # # cache the payload if --defer used or send to Azure + # return cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, + # flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, + # cluster_name=cluster_name, setter_arg_name='flux_configuration') + + # def create_kustomization(self, resource_group_name, cluster_type, cluster_name, name, kustomization_name, + # dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): + # # Determine ClusterRP + # cluster_rp = get_cluster_rp(cluster_type) - # Validate the extension install if this is not a deferred command - if not self._is_deferred(): - self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name) - - flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name, cluster_rp, cluster_type, cluster_name, config_name) - - kustomization = KustomizationDefinition( - name=name, - path=path, - dependencies=dependencies, - timeout_in_seconds=timeout, - sync_interval_in_seconds=sync_interval, - retry_interval_in_seconds=retry_interval, - prune=prune, - validation=validation, - force=force - ) - - proposed_change = flux_configuration.kustomizations[:] + kustomization - validate_kustomization_list(proposed_change) - - upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') - flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name, setter_arg_name='flux_configuration') - return get_property(flux_configuration.kustomizations, name) + # # Validate the extension install if this is not a deferred command + # if not self._is_deferred(): + # self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + # self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + + # flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name, name) + + # kustomization = KustomizationDefinition( + # name=name, + # path=path, + # dependencies=dependencies, + # timeout_in_seconds=timeout, + # sync_interval_in_seconds=sync_interval, + # retry_interval_in_seconds=retry_interval, + # prune=prune, + # validation=validation, + # force=force + # ) + + # proposed_change = flux_configuration.kustomizations[:] + kustomization + # validate_kustomization_list(proposed_change) + + # upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') + # flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name, setter_arg_name='flux_configuration') + # return get_property(flux_configuration.kustomizations, name) def delete(self, client, resource_group_name, cluster_type, cluster_name, name): cluster_rp = get_cluster_rp(cluster_type) From e670203eb8e6084a126d03546254bacbf86af3d3 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 6 Jul 2021 12:39:31 -0700 Subject: [PATCH 19/61] Add formatters --- src/k8s-config/azext_k8s_config/commands.py | 30 +++++++---- src/k8s-config/azext_k8s_config/format.py | 58 +++++++++++++++++++++ 2 files changed, 77 insertions(+), 11 deletions(-) create mode 100644 src/k8s-config/azext_k8s_config/format.py diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 6fb255f386f..1e82a162a7f 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -10,6 +10,14 @@ k8s_config_extension_client, k8s_config_sourcecontrol_client ) +from .format import ( + fluxconfig_list_table_format, + fluxconfig_show_table_format, + extension_list_table_format, + extension_show_table_format, + sourcecontrol_list_table_format, + sourcecontrol_show_table_format +) def load_command_table(self, _): @@ -30,20 +38,20 @@ def load_command_table(self, _): with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_preview=True) as g: g.custom_command('create', 'flux_config_create') - g.command('list', "list") - g.custom_command('show', 'flux_config_show') + g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) + g.custom_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) g.custom_command('delete', 'flux_config_delete', confirmation=True) - g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) - g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) + # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) + # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: g.custom_command('create', 'extension_create') - g.custom_command('list', "extension_list") - g.custom_command('show', 'extension_show') + g.custom_command('list', "extension_list", table_transformer=extension_list_table_format) + g.custom_command('show', 'extension_show', table_transformer=extension_show_table_format) g.custom_command('delete', 'extension_delete', confirmation=True) - # with self.command_group('k8s-config source', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client) as g: - # g.custom_command('create', 'source_create') - # g.custom_command('list', 'list_k8sconfiguration') - # g.custom_show_command('show', 'show_k8sconfiguration') - # g.custom_command('delete', 'delete_k8sconfiguration', confirmation=True) + with self.command_group('k8s-config flux-v1', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client) as g: + g.custom_command('create', 'sourcecontrol_create') + g.custom_command('list', 'sourcecontrol_list', table_transformer=sourcecontrol_list_table_format) + g.custom_show_command('show', 'sourcecontrol_show', table_transformer=sourcecontrol_show_table_format) + g.custom_command('delete', 'sourcecontrol_delete', confirmation=True) diff --git a/src/k8s-config/azext_k8s_config/format.py b/src/k8s-config/azext_k8s_config/format.py new file mode 100644 index 00000000000..b06fcb6f9b9 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/format.py @@ -0,0 +1,58 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from collections import OrderedDict + + +def sourcecontrol_list_table_format(results): + return [__get_sourcecontrolconfig_table_row(result) for result in results] + + +def sourcecontrol_show_table_format(result): + return __get_sourcecontrolconfig_table_row(result) + + +def __get_sourcecontrolconfig_table_row(result): + return OrderedDict([ + ('name', result['name']), + ('repositoryUrl', result['repositoryUrl']), + ('operatorName', result['operatorInstanceName']), + ('operatorNamespace', result['operatorNamespace']), + ('scope', result['operatorScope']), + ('provisioningState', result['provisioningState']) + ]) + + +def extension_list_table_format(results): + return [__get_extension_table_row(result) for result in results] + + +def extension_show_table_format(result): + return __get_extension_table_row(result) + + +def __get_extension_table_row(result): + return OrderedDict([ + ('name', result['name']), + ('extensionType', result['extensionType']), + ('version', result['version']), + ('installState', result['installState']), + ('lastModifiedTime', result['lastModifiedTime']) + ]) + + +def fluxconfig_list_table_format(results): + return [__get_fluxconfig_table_row(result) for result in results] + + +def fluxconfig_show_table_format(result): + return __get_fluxconfig_table_row(result) + + +def __get_fluxconfig_table_row(result): + print(result) + return OrderedDict([ + ('name', result['name']), + ]) \ No newline at end of file From 3ee12a63e29038165aad435bced4270cec26cb10 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 6 Jul 2021 13:08:06 -0700 Subject: [PATCH 20/61] Add scc provider --- src/k8s-config/azext_k8s_config/_params.py | 189 ++++++++++++------ src/k8s-config/azext_k8s_config/custom.py | 61 ++++-- .../providers/FluxConfigurationProvider.py | 1 - .../SourceControlConfigurationProvider.py | 71 ++++++- src/k8s-config/azext_k8s_config/utils.py | 10 + src/k8s-config/azext_k8s_config/validators.py | 12 ++ 6 files changed, 259 insertions(+), 85 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 0a7b751130f..9232ad6ae13 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -11,7 +11,7 @@ get_three_state_flag, tags_type ) -from .validators import validate_configuration_name, validate_namespace +from .validators import validate_configuration_name, validate_configuration_type, validate_namespace, validate_operator_instance_name, validate_operator_namespace from .action import ( KustomizationAddAction, AddConfigurationProtectedSettings, @@ -141,80 +141,139 @@ def load_arguments(self, _): help='Specify the target namespace to install to for the extension instance. This' ' parameter is required if extension scope is set to \'namespace\'') - with self.argument_context('k8s-config flux source') as c: + + with self.argument_context('k8s-config flux-v1 create') as c: + c.argument('repository_url', + options_list=['--repository-url', '-u'], + help='Url of the source control repository') c.argument('scope', - options_list=['--scope', '-s'], arg_type=get_enum_type(['namespace', 'cluster']), - help="Specify scope of the operator to be 'namespace' or 'cluster'") - c.argument('namespace', - help='Namespace to deploy the configuration', - options_list=['--namespace', '--ns'], - validator=validate_namespace) - c.argument('kind', - arg_type=get_enum_type([consts.GIT]), - help='Source kind to reconcile') - c.argument('url', - options_list=['--url', '-u'], - help='URL of the source to reconcile') - c.argument('timeout', - help='Maximum time to reconcile the source before timing out') - c.argument('sync_interval', - options_list=['--interval', '--sync-interval'], - help='Time between reconciliations of the source on the cluster') - c.argument('branch', - arg_group="Repo Ref", - help='Branch to reconcile with the git source') - c.argument('tag', - arg_group="Repo Ref", - help='Tag to reconcile with the git source') - c.argument('semver', - arg_group="Repo Ref", - help='Semver range to reconcile with the git source') - c.argument('commit', - arg_group="Repo Ref", - help='Specific commit to reconcile with the git source') + help='''Specify scope of the operator to be 'namespace' or 'cluster' ''') + c.argument('configuration_type', + validator=validate_configuration_type, + arg_type=get_enum_type(['sourceControlConfiguration']), + help='Type of the configuration') + c.argument('enable_helm_operator', + arg_group="Helm Operator", + arg_type=get_three_state_flag(), + options_list=['--enable-helm-operator', '--enable-hop'], + help='Enable support for Helm chart deployments') + c.argument('helm_operator_params', + arg_group="Helm Operator", + options_list=['--helm-operator-params', '--hop-params'], + help='Chart values for the Helm Operator (if enabled)') + c.argument('helm_operator_chart_version', + arg_group="Helm Operator", + options_list=['--helm-operator-chart-version', '--hop-chart-version'], + help='Chart version of the Helm Operator (if enabled)') + c.argument('operator_params', + arg_group="Operator", + help='Parameters for the Operator') + c.argument('operator_instance_name', + arg_group="Operator", + help='Instance name of the Operator', + validator=validate_operator_instance_name) + c.argument('operator_namespace', + arg_group="Operator", + help='Namespace in which to install the Operator', + validator=validate_operator_namespace) + c.argument('operator_type', + arg_group="Operator", + help='''Type of the operator. Valid value is 'flux' ''') c.argument('ssh_private_key', arg_group="Auth", - help='Base64-encoded private ssh key for private repository sync') + help='Specify Base64-encoded private ssh key for private repository sync') c.argument('ssh_private_key_file', arg_group="Auth", - help='Filepath to private ssh key for private repository sync') + help='Specify filepath to private ssh key for private repository sync') c.argument('https_user', arg_group="Auth", - help='HTTPS username for private repository sync') + help='Specify HTTPS username for private repository sync') c.argument('https_key', arg_group="Auth", - help='HTTPS token/password for private repository sync') - c.argument('known_hosts', - arg_group="Auth", - help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') - c.argument('known_hosts_file', + help='Specify HTTPS token/password for private repository sync') + c.argument('ssh_known_hosts', arg_group="Auth", - help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') - c.argument('local_auth_ref', - options_list=['--local-auth-ref'], + help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') + c.argument('ssh_known_hosts_file', arg_group="Auth", - help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') + help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') - with self.argument_context('k8s-config flux kustomization') as c: - c.argument('kustomization_name', - help='Specify the name of the kustomization to add to the configuration') - c.argument('path', - help='Specify the path in the source that the kustomization should apply') - c.argument('dependencies', - options_list=['--depends', '--dependencies'], - help='Specify the names of kustomization dependencies') - c.argument('timeout', - help='Maximum time to reconcile the kustomization before timing out') - c.argument('sync_interval', - options_list=['--interval', '--sync-interval'], - help='Time between reconciliations of the kustomization on the cluster') - c.argument('retry_interval', - help='Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval') - c.argument('prune', - help='Whether to garbage collect resources deployed by the kustomization on the cluster') - c.argument('force', - help='Whether to re-create resources that cannot be updated on the cluster (i.e. jobs)') - c.argument('validation', - arg_type=get_enum_type(['none', 'client', 'server']), - help='Specify whether to dry-run manifests at the client or at the apiserver level before applying them to the cluster.') + + # with self.argument_context('k8s-config flux source') as c: + # c.argument('scope', + # options_list=['--scope', '-s'], + # arg_type=get_enum_type(['namespace', 'cluster']), + # help="Specify scope of the operator to be 'namespace' or 'cluster'") + # c.argument('namespace', + # help='Namespace to deploy the configuration', + # options_list=['--namespace', '--ns'], + # validator=validate_namespace) + # c.argument('kind', + # arg_type=get_enum_type([consts.GIT]), + # help='Source kind to reconcile') + # c.argument('url', + # options_list=['--url', '-u'], + # help='URL of the source to reconcile') + # c.argument('timeout', + # help='Maximum time to reconcile the source before timing out') + # c.argument('sync_interval', + # options_list=['--interval', '--sync-interval'], + # help='Time between reconciliations of the source on the cluster') + # c.argument('branch', + # arg_group="Repo Ref", + # help='Branch to reconcile with the git source') + # c.argument('tag', + # arg_group="Repo Ref", + # help='Tag to reconcile with the git source') + # c.argument('semver', + # arg_group="Repo Ref", + # help='Semver range to reconcile with the git source') + # c.argument('commit', + # arg_group="Repo Ref", + # help='Specific commit to reconcile with the git source') + # c.argument('ssh_private_key', + # arg_group="Auth", + # help='Base64-encoded private ssh key for private repository sync') + # c.argument('ssh_private_key_file', + # arg_group="Auth", + # help='Filepath to private ssh key for private repository sync') + # c.argument('https_user', + # arg_group="Auth", + # help='HTTPS username for private repository sync') + # c.argument('https_key', + # arg_group="Auth", + # help='HTTPS token/password for private repository sync') + # c.argument('known_hosts', + # arg_group="Auth", + # help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') + # c.argument('known_hosts_file', + # arg_group="Auth", + # help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') + # c.argument('local_auth_ref', + # options_list=['--local-auth-ref'], + # arg_group="Auth", + # help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') + + # with self.argument_context('k8s-config flux kustomization') as c: + # c.argument('kustomization_name', + # help='Specify the name of the kustomization to add to the configuration') + # c.argument('path', + # help='Specify the path in the source that the kustomization should apply') + # c.argument('dependencies', + # options_list=['--depends', '--dependencies'], + # help='Specify the names of kustomization dependencies') + # c.argument('timeout', + # help='Maximum time to reconcile the kustomization before timing out') + # c.argument('sync_interval', + # options_list=['--interval', '--sync-interval'], + # help='Time between reconciliations of the kustomization on the cluster') + # c.argument('retry_interval', + # help='Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval') + # c.argument('prune', + # help='Whether to garbage collect resources deployed by the kustomization on the cluster') + # c.argument('force', + # help='Whether to re-create resources that cannot be updated on the cluster (i.e. jobs)') + # c.argument('validation', + # arg_type=get_enum_type(['none', 'client', 'server']), + # help='Specify whether to dry-run manifests at the client or at the apiserver level before applying them to the cluster.') diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 6bc9f47548e..b342b468ae8 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -3,11 +3,40 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +from azext_k8s_config.providers.SourceControlConfigurationProvider import SourceControlConfigurationProvider from .providers.ExtensionProvider import ExtensionProvider from .providers.FluxConfigurationProvider import FluxConfigurationProvider from .utils import get_cluster_rp from . import consts +# Source Control Configuration Methods + +def sourcecontrol_create(cmd, client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, + operator_instance_name=None, operator_namespace='default', + helm_operator_chart_version='1.2.0', operator_type='flux', operator_params='', + ssh_private_key='', ssh_private_key_file='', https_user='', https_key='', + ssh_known_hosts='', ssh_known_hosts_file='', enable_helm_operator=None, + helm_operator_params=''): + provider = SourceControlConfigurationProvider(cmd) + return provider.create(resource_group_name, cluster_name, name, repository_url, scope, cluster_type, + operator_instance_name, operator_namespace, helm_operator_chart_version, operator_type, + operator_params, ssh_private_key, ssh_private_key_file, https_user, https_key, + ssh_known_hosts, ssh_known_hosts_file, enable_helm_operator, helm_operator_params) + +def sourcecontrol_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = SourceControlConfigurationProvider(cmd) + return provider.show(resource_group_name, cluster_type, cluster_name, name) + + +def sourcecontrol_list(cmd, client, resource_group_name, cluster_type, cluster_name): + provider = SourceControlConfigurationProvider(cmd) + return provider.list(resource_group_name, cluster_type, cluster_name) + + +def sourcecontrol_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = SourceControlConfigurationProvider(cmd) + return provider.delete(resource_group_name, cluster_type, cluster_name, name) + # Flux Configuration Methods @@ -30,24 +59,24 @@ def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_n known_hosts_file, kustomization) -def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, - scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, - branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, - ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None): +# def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, +# scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, +# branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, +# ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, +# known_hosts_file=None): - provider = FluxConfigurationProvider(cmd) - return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, - branch, tag, semver, commit, local_auth_ref, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, - known_hosts_file) - -def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, kustomization_name, - dependencies=None, timeout=None, sync_interval=None, retry_interval=None, path='', prune=False, validation='none', force=False): +# provider = FluxConfigurationProvider(cmd) +# return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, +# branch, tag, semver, commit, local_auth_ref, ssh_private_key, +# ssh_private_key_file, https_user, https_key, known_hosts, +# known_hosts_file) + +# def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, kustomization_name, +# dependencies=None, timeout=None, sync_interval=None, retry_interval=None, path='', prune=False, validation='none', force=False): - provider = FluxConfigurationProvider(cmd) - return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, - dependencies, timeout, sync_interval, retry_interval, path, prune, validation, force) +# provider = FluxConfigurationProvider(cmd) +# return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, +# dependencies, timeout, sync_interval, retry_interval, path, prune, validation, force) def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): provider = FluxConfigurationProvider(cmd) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 5226bfa4b8c..fd302a424a2 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -24,7 +24,6 @@ from ..vendored_sdks.v2021_06_01_preview.models import ( FluxConfiguration, GitRepositoryDefinition, - KustomizationDefinition, RepositoryRefDefinition, ) from .ExtensionProvider import ExtensionProvider diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py index ce4f77d73cb..8c421f1803c 100644 --- a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py @@ -1,9 +1,15 @@ +from azext_k8s_config.validators import validate_cc_registration, validate_known_hosts, validate_url_with_params from azure.cli.core.azclierror import ResourceNotFoundError from azure.core.exceptions import HttpResponseError from knack.log import get_logger from .._client_factory import k8s_config_sourcecontrol_client -from ..utils import get_cluster_rp +from ..utils import fix_compliance_state, get_cluster_rp, get_data_from_key_or_file, get_protected_settings + +from ..vendored_sdks.v2021_03_01.models import ( + HelmOperatorProperties, + SourceControlConfiguration +) logger = get_logger(__name__) @@ -47,6 +53,65 @@ def delete(self, resource_group_name, cluster_type, cluster_name, name): cluster_rp = get_cluster_rp(cluster_type) return self.client.delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + # pylint: disable=too-many-locals + def create(self, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, + operator_instance_name, operator_namespace, helm_operator_chart_version, operator_type, + operator_params, ssh_private_key, ssh_private_key_file, https_user, https_key, + ssh_known_hosts, ssh_known_hosts_file, enable_helm_operator, helm_operator_params): + + """Create a new Kubernetes Source Control Configuration. + + """ + # Determine ClusterRP + cluster_rp = get_cluster_rp(cluster_type) + + # Determine operatorInstanceName + if operator_instance_name is None: + operator_instance_name = name + + # Create helmOperatorProperties object + helm_operator_properties = None + if enable_helm_operator: + helm_operator_properties = HelmOperatorProperties() + helm_operator_properties.chart_version = helm_operator_chart_version.strip() + helm_operator_properties.chart_values = helm_operator_params.strip() + + protected_settings = get_protected_settings(ssh_private_key, + ssh_private_key_file, + https_user, + https_key) + knownhost_data = get_data_from_key_or_file(ssh_known_hosts, ssh_known_hosts_file) + if knownhost_data: + validate_known_hosts(knownhost_data) + + # Flag which parameters have been set and validate these settings against the set repository url + ssh_private_key_set = ssh_private_key != '' or ssh_private_key_file != '' + known_hosts_contents_set = knownhost_data != '' + https_auth_set = https_user != '' and https_key != '' + validate_url_with_params(repository_url, + ssh_private_key_set=ssh_private_key_set, + known_hosts_contents_set=known_hosts_contents_set, + https_auth_set=https_auth_set) + + # Validate that the subscription is registered to Microsoft.KubernetesConfiguration + validate_cc_registration(self.cmd) + + # Create sourceControlConfiguration object + source_control_configuration = SourceControlConfiguration( + repository_url=repository_url, + operator_namespace=operator_namespace, + operator_instance_name=operator_instance_name, + operator_type=operator_type, + operator_params=operator_params, + configuration_protected_settings=protected_settings, + operator_scope=scope, + ssh_known_hosts_contents=knownhost_data, + enable_helm_operator=enable_helm_operator, + helm_operator_properties=helm_operator_properties + ) + + # Try to create the resource + config = self.client.create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, + name, source_control_configuration) - def create(): - pass \ No newline at end of file + return fix_compliance_state(config) \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 86add539b1c..627fc091b72 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -116,3 +116,13 @@ def from_base64(base64_str): def to_base64(raw_data): bytes_data = raw_data.encode('utf-8') return base64.b64encode(bytes_data).decode('utf-8') + + +def fix_compliance_state(config): + # If we get Compliant/NonCompliant as compliance_sate, change them before returning + if config.compliance_status.compliance_state.lower() == 'noncompliant': + config.compliance_status.compliance_state = 'Failed' + elif config.compliance_status.compliance_state.lower() == 'compliant': + config.compliance_status.compliance_state = 'Installed' + + return config \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index cde2a58734b..68d2dec394a 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -24,6 +24,13 @@ logger = get_logger(__name__) +# Parameter-Level Validation +def validate_configuration_type(configuration_type): + if configuration_type.lower() != 'sourcecontrolconfiguration': + raise InvalidArgumentValueError( + 'Invalid configuration-type', + 'Try specifying the valid value "sourceControlConfiguration"') + def validate_namespace(namespace): if namespace.namespace: @@ -39,6 +46,11 @@ def validate_configuration_name(namespace): __validate_k8s_name(namespace.name, "--name", 63) +def validate_operator_namespace(namespace): + if namespace.operator_namespace: + __validate_k8s_name(namespace.operator_namespace, "--operator-namespace", 23) + + def validate_kustomization(values): required_keys = consts.REQUIRED_KUSTOMIZATION_KEYS for item in values: From 549e05f6b7b87fe8dd75aa30a7f4f705e247c7ea Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 6 Jul 2021 14:20:31 -0700 Subject: [PATCH 21/61] Add help text for k8s-config fluxv1 --- src/k8s-config/azext_k8s_config/_help.py | 58 ++++++++++++++++++++- src/k8s-config/azext_k8s_config/commands.py | 2 +- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 0ecf5db84d4..15b38f9ca0e 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -6,12 +6,66 @@ from knack.help_files import helps # pylint: disable=unused-import - helps['k8s-config'] = """ type: group short-summary: Commands to manage resources from Microsoft.KubernetesConfiguration. """ +helps['k8s-config flux-v1'] = """ + type: group + short-summary: Commands to manage Flux V1 Kubernetes configurations. +""" + +helps['k8s-config flux-v1 create'] = """ + type: command + short-summary: Create a Kubernetes configuration. + examples: + - name: Create a Kubernetes configuration + text: |- + az k8s-config flux-v1 create --resource-group MyResourceGroup --cluster-name MyClusterName \\ + --cluster-type connectedClusters --name MyGitConfig --operator-instance-name OperatorInst01 \\ + --operator-namespace OperatorNamespace01 --operator-type flux --operator-params "'--git-readonly'" \\ + --repository-url git://github.com/fluxHowTo/flux-get-started --enable-helm-operator \\ + --helm-operator-chart-version 1.2.0 --scope namespace --helm-operator-params '--set helm.versions=v3' \\ + --ssh-private-key '' --ssh-private-key-file '' --https-user '' --https-key '' \\ + --ssh-known-hosts '' --ssh-known-hosts-file '' +""" + +helps['k8s-config flux-v1 list'] = """ + type: command + short-summary: List Kubernetes configurations. + examples: + - name: List all Kubernetes configurations of a cluster + text: |- + az k8s-config flux-v1 list --resource-group MyResourceGroup --cluster-name MyClusterName \\ + --cluster-type connectedClusters +""" + +helps['k8s-config flux-v1 delete'] = """ + type: command + short-summary: Delete a Kubernetes configuration. + examples: + - name: Delete a Kubernetes configuration + text: |- + az k8s-config flux-v1 delete --resource-group MyResourceGroup --cluster-name MyClusterName \\ + --cluster-type connectedClusters --name MyConfigurationName +""" + +helps['k8s-config flux-v1 show'] = """ + type: command + short-summary: Show details of a Kubernetes configuration. + examples: + - name: Show a Kubernetes configuration + text: |- + az k8s-config flux-v1 show --resource-group MyResourceGroup --cluster-name MyClusterName \\ + --cluster-type connectedClusters --name MyConfigurationName +""" + +helps['k8s-config flux'] = """ + type: group + short-summary: Commands to manage Flux V2 Kubernetes configurations. +""" + helps['k8s-config flux create'] = """ type: command short-summary: Create a Kubernetes Flux Configuration. @@ -59,4 +113,4 @@ text: |- az k8s-config flux delete --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myconfig -""" +""" \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 1e82a162a7f..22295dce2e0 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -50,7 +50,7 @@ def load_command_table(self, _): g.custom_command('show', 'extension_show', table_transformer=extension_show_table_format) g.custom_command('delete', 'extension_delete', confirmation=True) - with self.command_group('k8s-config flux-v1', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client) as g: + with self.command_group('k8s-config flux-v1', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client, deprecate_info=self.deprecate(redirect='k8s-config flux')) as g: g.custom_command('create', 'sourcecontrol_create') g.custom_command('list', 'sourcecontrol_list', table_transformer=sourcecontrol_list_table_format) g.custom_show_command('show', 'sourcecontrol_show', table_transformer=sourcecontrol_show_table_format) From 4899d0c0393f5c7f72dbf96ab4fd21e52e327ed0 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 8 Jul 2021 12:40:57 -0700 Subject: [PATCH 22/61] Add help text for extension --- src/k8s-config/azext_k8s_config/_help.py | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 15b38f9ca0e..3a464114bc3 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -113,4 +113,50 @@ text: |- az k8s-config flux delete --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myconfig +""" + +helps['k8s-config extension'] = """ + type: group + short-summary: Commands to manage Flux V2 Kubernetes configurations. +""" + +helps['k8s-config extension create'] = """ + type: command + short-summary: Create a Kubernetes Extension. + examples: + - name: Create a Kubernetes Extension + text: |- + az k8s-config extension create --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myextension --extension-type microsoft.openservicemesh \\ + --scope cluster --release-train stable +""" + +helps['k8s-config extension list'] = """ + type: command + short-summary: List Kubernetes Flux Configurations. + examples: + - name: List all Kubernetes Flux Configurations on a cluster + text: |- + az k8s-config extension list --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters +""" + +helps['k8s-config extension show'] = """ + type: command + short-summary: Show a Kubernetes Flux Configuration. + examples: + - name: Show details of a Kubernetes Flux Configuration + text: |- + az k8s-config extension show --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myextension +""" + +helps['k8s-config extension delete'] = """ + type: command + short-summary: Delete a Kubernetes Flux Configuration. + examples: + - name: Delete an existing Kubernetes Flux Configuration + text: |- + az k8s-config extension delete --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myextension """ \ No newline at end of file From c32b09405eae1b32a351e37782ee08159c59c6f8 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 8 Jul 2021 12:41:22 -0700 Subject: [PATCH 23/61] Allow force delete of extension and fluxconfiguration --- src/k8s-config/azext_k8s_config/_params.py | 9 +- src/k8s-config/azext_k8s_config/commands.py | 4 +- src/k8s-config/azext_k8s_config/custom.py | 45 +++--- .../providers/ExtensionProvider.py | 43 +++--- .../providers/FluxConfigurationProvider.py | 141 ++++++++++-------- 5 files changed, 134 insertions(+), 108 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 9232ad6ae13..7b9d170e80e 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -99,6 +99,10 @@ def load_arguments(self, _): help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", nargs='+') + with self.argument_context('k8s-config flux delete') as c: + c.argument('force', + help='Specify whether to force delete the flux configuration from the cluster.') + with self.argument_context('k8s-config extension create') as c: c.argument('scope', arg_type=get_enum_type(['cluster', 'namespace']), @@ -140,7 +144,10 @@ def load_arguments(self, _): c.argument('target_namespace', help='Specify the target namespace to install to for the extension instance. This' ' parameter is required if extension scope is set to \'namespace\'') - + + with self.argument_context('k8s-config extension delete') as c: + c.argument('force', + help='Specify whether to force delete the extension from the cluster.') with self.argument_context('k8s-config flux-v1 create') as c: c.argument('repository_url', diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 22295dce2e0..a9d3c39c6ec 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -41,8 +41,8 @@ def load_command_table(self, _): g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) g.custom_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) g.custom_command('delete', 'flux_config_delete', confirmation=True) - # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) - # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) + g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) + g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: g.custom_command('create', 'extension_create') diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index b342b468ae8..de238821492 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -45,6 +45,11 @@ def flux_config_show(cmd, client, resource_group_name, cluster_type, cluster_nam return provider.show(resource_group_name, cluster_type, cluster_name, name) +def flux_config_list(cmd, client, resource_group_name, cluster_type, cluster_name): + provider = FluxConfigurationProvider(cmd) + return provider.list(resource_group_name, cluster_type, cluster_name) + + # pylint: disable=too-many-locals def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, @@ -59,28 +64,28 @@ def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_n known_hosts_file, kustomization) -# def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, -# scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, -# branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, -# ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, -# known_hosts_file=None): +def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, + scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, + branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, + ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + known_hosts_file=None): -# provider = FluxConfigurationProvider(cmd) -# return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, -# branch, tag, semver, commit, local_auth_ref, ssh_private_key, -# ssh_private_key_file, https_user, https_key, known_hosts, -# known_hosts_file) - -# def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, kustomization_name, -# dependencies=None, timeout=None, sync_interval=None, retry_interval=None, path='', prune=False, validation='none', force=False): + provider = FluxConfigurationProvider(cmd) + return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, + branch, tag, semver, commit, local_auth_ref, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, + known_hosts_file) + +def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, kustomization_name, + dependencies=None, timeout=None, sync_interval=None, retry_interval=None, path='', prune=False, validation='none', force=False): -# provider = FluxConfigurationProvider(cmd) -# return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, -# dependencies, timeout, sync_interval, retry_interval, path, prune, validation, force) + provider = FluxConfigurationProvider(cmd) + return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, + dependencies, timeout, sync_interval, retry_interval, path, prune, validation, force) -def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): +def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False): provider = FluxConfigurationProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name) + return provider.delete(resource_group_name, cluster_type, cluster_name, name, force) # Extension Methods @@ -105,6 +110,6 @@ def extension_create(cmd, client, resource_group_name, cluster_type, cluster_nam configuration_settings, configuration_protected_settings, configuration_settings_file, configuration_protected_settings_file) -def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): +def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False): provider = ExtensionProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name) + return provider.delete(resource_group_name, cluster_type, cluster_name, name, force) diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index 10da8a2d567..3d7d9e733e7 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -35,7 +35,7 @@ def ExtensionFactory(extension_name): 'microsoft.azuremonitor.containers': ContainerInsights, 'microsoft.azuredefender.kubernetes': AzureDefender, 'microsoft.azureml.kubernetes': AzureMLKubernetes, - 'microsoft.flux': DefaultExtension, + 'microsoft.flux': DefaultExtensionWithIdentity, 'cassandradatacentersoperator': DefaultExtensionWithIdentity, } @@ -78,9 +78,12 @@ def list(self, resource_group_name, cluster_type, cluster_name): return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - def delete(self, resource_group_name, cluster_type, cluster_name, name): + def delete(self, resource_group_name, cluster_type, cluster_name, name, force): cluster_rp = get_cluster_rp(cluster_type) - return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + + if not force: + logger.info("Delting the flux configuration from the cluster. This may take a minute...") + return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name, force_delete=force) def create(self, resource_group_name, cluster_type, cluster_name, name, @@ -148,9 +151,9 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, # Create identity, if required if create_identity: - extension_instance.identity, extension_instance.location = self.__create_identity(resource_group_name, cluster_rp, cluster_type, cluster_name) + extension_instance = self.__add_identity(extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name) - # Try to create the resource + logger.info("Starting extension creation on the cluster. This might take a minute...") return self.client.begin_create(resource_group_name, cluster_rp, cluster_type, cluster_name, name, extension_instance) def __validate_scope_and_namespace(self, scope, release_namespace, target_namespace): @@ -179,7 +182,7 @@ def __validate_version_and_auto_upgrade(self, version, auto_upgrade_minor_versio auto_upgrade_minor_version = False - def __create_identity(self, resource_group_name, cluster_rp, cluster_type, cluster_name): + def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name): subscription_id = get_subscription_id(self.cmd.cli_ctx) resources = cf_resources(self.cmd.cli_ctx, subscription_id) @@ -189,22 +192,24 @@ def __create_identity(self, resource_group_name, cluster_rp, cluster_type, clust cluster_type, cluster_name) - if cluster_rp == 'Microsoft.Kubernetes': - parent_api_version = '2020-01-01-preview' - elif cluster_rp == 'Microsoft.ResourceConnector': - parent_api_version = '2020-09-15-privatepreview' - elif cluster_rp == 'Microsoft.ContainerService': - parent_api_version = '2017-07-01' - else: - raise InvalidArgumentValueError( - "Error! Cluster type '{}' is not supported for extension identity".format(cluster_type) - ) - + parent_api_version = self.__get_parent_api_version(cluster_rp) try: resource = resources.get_by_id(cluster_resource_id, parent_api_version) location = str(resource.location.lower()) - except CloudError as ex: + except HttpResponseError as ex: raise ex identity_type = "SystemAssigned" + + extension_instance.identity = Identity(type=identity_type) + extension_instance.location = location + return extension_instance - return Identity(type=identity_type), location \ No newline at end of file + def __get_parent_api_version(self, cluster_rp): + if cluster_rp == 'Microsoft.Kubernetes': + return '2020-01-01-preview' + elif cluster_rp == 'Microsoft.ResourceConnector': + return '2020-09-15-privatepreview' + elif cluster_rp == 'Microsoft.ContainerService': + return '2017-07-01' + else: + raise InvalidArgumentValueError("Error! Cluster RP '{}' is not supported for extension identity".format(cluster_rp)) \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index fd302a424a2..eb414bfea86 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -69,6 +69,10 @@ def show(self, resource_group_name, cluster_type, cluster_name, name): recommendation = '' raise ResourceNotFoundError(message, recommendation) from ex + def list(self, resource_group_name, cluster_type, cluster_name): + cluster_rp = get_cluster_rp(cluster_type) + return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) + # pylint: disable=too-many-locals def create(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', @@ -106,75 +110,79 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None return self.client.begin_create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) - # def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', - # kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, - # ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - # known_hosts_file=None): - # # Determine the cluster RP - # cluster_rp = get_cluster_rp(cluster_type) - # dp_source_kind = "" - # git_repository = None - - # # Validate the extension install if this is not a deferred command - # if not self._is_deferred(): - # self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - # self._validate_extension_install(resource_group_name, cluster_type, cluster_name) - - # if kind == consts.GIT: - # dp_source_kind = consts.GIT_REPOSITORY - # git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, - # ssh_private_key_file, https_user, https_key, known_hosts, - # known_hosts_file, local_auth_ref) + def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', + kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, + ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + known_hosts_file=None): + # Determine the cluster RP + cluster_rp = get_cluster_rp(cluster_type) + dp_source_kind = "" + git_repository = None + + # Validate the extension install if this is not a deferred command + if not self._is_deferred(): + self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + + if kind == consts.GIT: + dp_source_kind = consts.GIT_REPOSITORY + git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, + known_hosts_file, local_auth_ref) - # flux_configuration = FluxConfiguration( - # scope=scope, - # namespace=namespace, - # source_kind=dp_source_kind, - # git_repository=git_repository, - # kustomizations=[] - # ) - - # # cache the payload if --defer used or send to Azure - # return cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, - # flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, - # cluster_name=cluster_name, setter_arg_name='flux_configuration') - - # def create_kustomization(self, resource_group_name, cluster_type, cluster_name, name, kustomization_name, - # dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): - # # Determine ClusterRP - # cluster_rp = get_cluster_rp(cluster_type) + flux_configuration = FluxConfiguration( + scope=scope, + namespace=namespace, + source_kind=dp_source_kind, + git_repository=git_repository, + kustomizations=[] + ) + + # cache the payload if --defer used or send to Azure + return cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, + flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, + cluster_name=cluster_name, setter_arg_name='flux_configuration') + + def create_kustomization(self, resource_group_name, cluster_type, cluster_name, name, kustomization_name, + dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): + # Determine ClusterRP + cluster_rp = get_cluster_rp(cluster_type) - # # Validate the extension install if this is not a deferred command - # if not self._is_deferred(): - # self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - # self._validate_extension_install(resource_group_name, cluster_type, cluster_name) - - # flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name, name) - - # kustomization = KustomizationDefinition( - # name=name, - # path=path, - # dependencies=dependencies, - # timeout_in_seconds=timeout, - # sync_interval_in_seconds=sync_interval, - # retry_interval_in_seconds=retry_interval, - # prune=prune, - # validation=validation, - # force=force - # ) - - # proposed_change = flux_configuration.kustomizations[:] + kustomization - # validate_kustomization_list(proposed_change) - - # upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') - # flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name, setter_arg_name='flux_configuration') - # return get_property(flux_configuration.kustomizations, name) - - def delete(self, client, resource_group_name, cluster_type, cluster_name, name): + # Validate the extension install if this is not a deferred command + if not self._is_deferred(): + self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + + flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name) + + kustomization = KustomizationDefinition( + name=name, + path=path, + dependencies=dependencies, + timeout_in_seconds=timeout, + sync_interval_in_seconds=sync_interval, + retry_interval_in_seconds=retry_interval, + prune=prune, + validation=validation, + force=force + ) + + proposed_change = flux_configuration.kustomizations[:] + kustomization + validate_kustomization_list(proposed_change) + + upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') + flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name, setter_arg_name='flux_configuration') + return get_property(flux_configuration.kustomizations, name) + + def delete(self, client, resource_group_name, cluster_type, cluster_name, name, force): cluster_rp = get_cluster_rp(cluster_type) - return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + + if not force: + logger.info("Delting the flux configuration from the cluster. This may take a minute...") + return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name, force_delete=force) def _is_deferred(self): + return if '--defer' in self.cmd.cli_ctx.data.get('safe_params'): return True return False @@ -197,8 +205,9 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster found_flux_extension = True break if not found_flux_extension: - logger.warning("'Micrsoft.Flux' extension not found on the cluster, installing it now. This may take a minute...") - self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE, release_train="preview") + logger.info("'Micrsoft.Flux' extension not found on the cluster, installing it now. This may take a minute...") + self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE, scope="cluster", release_namespace="flux-system").result() + logger.info("'Microsoft.Flux' extension was successfully installed on the cluster") def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, local_auth_ref): From 7f95fec92a5d1f05cf8bd37f07e49c811c529930 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 9 Jul 2021 13:49:39 -0700 Subject: [PATCH 24/61] Add location to the extension model --- .../azext_k8s_config/providers/FluxConfigurationProvider.py | 2 +- .../vendored_sdks/v2021_05_01_preview/models/_models.py | 4 ++++ .../vendored_sdks/v2021_05_01_preview/models/_models_py3.py | 5 +++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index eb414bfea86..1ec54af9c62 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -206,7 +206,7 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster break if not found_flux_extension: logger.info("'Micrsoft.Flux' extension not found on the cluster, installing it now. This may take a minute...") - self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE, scope="cluster", release_namespace="flux-system").result() + self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE).result() logger.info("'Microsoft.Flux' extension was successfully installed on the cluster") def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py index 2ad2439168e..bdc94c0ad8c 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py @@ -273,6 +273,8 @@ class Extension(ProxyResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str + :param location: Location of resource type + :type location: str :param identity: Identity of the Extension resource. :type identity: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Identity :ivar system_data: Top level metadata @@ -329,6 +331,7 @@ class Extension(ProxyResource): 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, + 'location': {'key': 'location', 'type': 'str'}, 'identity': {'key': 'identity', 'type': 'Identity'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, 'extension_type': {'key': 'properties.extensionType', 'type': 'str'}, @@ -350,6 +353,7 @@ def __init__( **kwargs ): super(Extension, self).__init__(**kwargs) + self.location = kwargs.get('location', None) self.identity = kwargs.get('identity', None) self.system_data = None self.extension_type = kwargs.get('extension_type', None) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py index ffc3547f685..3ef0d42a6a6 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py @@ -287,6 +287,8 @@ class Extension(ProxyResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str + :param location: Location of resource type + :type location: str :param identity: Identity of the Extension resource. :type identity: ~azure.mgmt.kubernetesconfiguration.v2021_05_01_preview.models.Identity :ivar system_data: Top level metadata @@ -343,6 +345,7 @@ class Extension(ProxyResource): 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, + 'location': {'key': 'location', 'type': 'str'}, 'identity': {'key': 'identity', 'type': 'Identity'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, 'extension_type': {'key': 'properties.extensionType', 'type': 'str'}, @@ -362,6 +365,7 @@ class Extension(ProxyResource): def __init__( self, *, + location: Optional[str] = None, identity: Optional["Identity"] = None, extension_type: Optional[str] = None, auto_upgrade_minor_version: Optional[bool] = True, @@ -374,6 +378,7 @@ def __init__( **kwargs ): super(Extension, self).__init__(**kwargs) + self.location = location self.identity = identity self.system_data = None self.extension_type = extension_type From e4ced73fc7667f37b175bbc5703b1db7476f7ec1 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 20 Jul 2021 15:30:59 -0700 Subject: [PATCH 25/61] Update with latest from k8s-extension --- .../partner_extensions/AzureDefender.py | 14 + .../partner_extensions/AzureMLKubernetes.py | 131 +++++-- .../partner_extensions/Cassandra.py | 61 +++ .../partner_extensions/ContainerInsights.py | 65 +-- .../partner_extensions/DefaultExtension.py | 15 +- .../partner_extensions/OpenServiceMesh.py | 161 ++++++++ .../PartnerExtensionModel.py | 12 +- .../data/azure_ml/cert_and_key_encoded.txt | 2 + .../tests/latest/data/azure_ml/test_cert.pem | 1 + .../tests/latest/data/azure_ml/test_key.pem | 1 + .../latest/recordings/test_k8s_extension.yaml | 370 ++++++++++++++++++ .../tests/latest/test_azureml_extension.py | 34 ++ .../latest/test_k8s_extension_scenario.py | 69 ++++ .../tests/latest/test_open_service_mesh.py | 23 ++ 14 files changed, 886 insertions(+), 73 deletions(-) create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py create mode 100644 src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/cert_and_key_encoded.txt create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_cert.pem create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_key.pem create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_azureml_extension.py create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_open_service_mesh.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py b/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py index e5d70cdbabd..61464a2da6d 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py @@ -60,3 +60,17 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t configuration_protected_settings=configuration_protected_settings ) return extension_instance, name, create_identity + + def Update(self, extension, auto_upgrade_minor_version, release_train, version): + """ExtensionType 'microsoft.azuredefender.kubernetes' specific validations & defaults for Update + Must create and return a valid 'ExtensionInstanceUpdate' object. + + """ + return Extension( + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version + ) + + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): + pass diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py index f42d62473b3..f188f76afc1 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py @@ -4,6 +4,9 @@ # -------------------------------------------------------------------------------------------- # pylint: disable=unused-argument +# pylint: disable=line-too-long +# pylint: disable=too-many-locals + import copy from hashlib import md5 from typing import Any, Dict, List, Tuple @@ -17,12 +20,7 @@ import azure.mgmt.storage.models import azure.mgmt.loganalytics import azure.mgmt.loganalytics.models -from ..vendored_sdks.v2021_05_01_preview.models import( - Extension, - ScopeCluster, - Scope -) -from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.core.azclierror import InvalidArgumentValueError, MutuallyExclusiveArgumentError from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id from azure.mgmt.resource.locks.models import ManagementLockObject from knack.log import get_logger @@ -30,12 +28,18 @@ from .._client_factory import cf_resources from .PartnerExtensionModel import PartnerExtensionModel +from ..vendored_sdks.v2021_05_01_preview.models import( + Extension, + ScopeCluster, + Scope +) logger = get_logger(__name__) -resource_tag = {'created_by': 'amlk8s-extension'} +resource_tag = {'created_by': 'Azure Arc-enabled ML'} +# pylint: disable=too-many-instance-attributes class AzureMLKubernetes(PartnerExtensionModel): def __init__(self): # constants for configuration settings. @@ -69,6 +73,14 @@ def __init__(self): self.SERVICE_BUS_JOB_STATE_TOPIC = 'jobstate-updatedby-computeprovider' self.SERVICE_BUS_JOB_STATE_SUB = 'compute-scheduler-jobstate' + # constants for enabling SSL in inference + self.sslKeyPemFile = 'sslKeyPemFile' + self.sslCertPemFile = 'sslCertPemFile' + self.allowInsecureConnections = 'allowInsecureConnections' + self.privateEndpointILB = 'privateEndpointILB' + self.privateEndpointNodeport = 'privateEndpointNodeport' + self.inferenceLoadBalancerHA = 'inferenceLoadBalancerHA' + # reference mapping self.reference_mapping = { self.RELAY_SERVER_CONNECTION_STRING: [self.RELAY_CONNECTION_STRING_KEY, self.RELAY_CONNECTION_STRING_DEPRECATED_KEY], @@ -142,13 +154,25 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t ) return extension_instance, name, create_identity + def Update(self, extension, auto_upgrade_minor_version, release_train, version): + return Extension( + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version + ) + + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): + # Give a warning message + logger.warning("If nvidia.com/gpu or fuse resource is not recognized by kubernetes after this deletion, " + "you probably have installed nvidia-device-plugin or fuse-device-plugin before installing AMLArc extension. " + "Please try to reinstall device plugins to fix this issue.") def __validate_config(self, configuration_settings, configuration_protected_settings): # perform basic validation of the input config config_keys = configuration_settings.keys() config_protected_keys = configuration_protected_settings.keys() dup_keys = set(config_keys) & set(config_protected_keys) - if len(dup_keys) > 0: + if dup_keys: for key in dup_keys: logger.warning( 'Duplicate keys found in both configuration settings and configuration protected setttings: %s', key) @@ -164,14 +188,14 @@ def __validate_config(self, configuration_settings, configuration_protected_sett if enable_inference: logger.warning("The installed AzureML extension for AML inference is experimental and not covered by customer support. Please use with discretion.") + self.__validate_scoring_fe_settings(configuration_settings, configuration_protected_settings) + self.__set_up_inference_ssl(configuration_settings, configuration_protected_settings) elif not (enable_training or enable_inference): raise InvalidArgumentValueError( "Please create Microsoft.AzureML.Kubernetes extension instance either " "for Machine Learning training or inference by specifying " f"'--configuration-settings {self.ENABLE_TRAINING}=true' or '--configuration-settings {self.ENABLE_INFERENCE}=true'") - self.__validate_scoring_fe_settings(configuration_settings, configuration_protected_settings) - configuration_settings[self.ENABLE_TRAINING] = configuration_settings.get(self.ENABLE_TRAINING, enable_training) configuration_settings[self.ENABLE_INFERENCE] = configuration_settings.get( self.ENABLE_INFERENCE, enable_inference) @@ -179,33 +203,63 @@ def __validate_config(self, configuration_settings, configuration_protected_sett configuration_protected_settings.pop(self.ENABLE_INFERENCE, None) def __validate_scoring_fe_settings(self, configuration_settings, configuration_protected_settings): - clusterPurpose = _get_value_from_config_protected_config( - 'clusterPurpose', configuration_settings, configuration_protected_settings) - if clusterPurpose and clusterPurpose not in ["DevTest", "FastProd"]: - raise InvalidArgumentValueError( - "Accepted values for '--configuration-settings clusterPurpose' " - "are 'DevTest' and 'FastProd'") - - feSslCert = _get_value_from_config_protected_config( - 'scoringFe.sslCert', configuration_settings, configuration_protected_settings) - sslKey = _get_value_from_config_protected_config( - 'scoringFe.sslKey', configuration_settings, configuration_protected_settings) + isTestCluster = _get_value_from_config_protected_config( + self.inferenceLoadBalancerHA, configuration_settings, configuration_protected_settings) + isTestCluster = str(isTestCluster).lower() == 'false' + if isTestCluster: + configuration_settings['clusterPurpose'] = 'DevTest' + else: + configuration_settings['clusterPurpose'] = 'FastProd' + feSslCertFile = configuration_protected_settings.get(self.sslCertPemFile) + feSslKeyFile = configuration_protected_settings.get(self.sslKeyPemFile) allowInsecureConnections = _get_value_from_config_protected_config( - 'allowInsecureConnections', configuration_settings, configuration_protected_settings) + self.allowInsecureConnections, configuration_settings, configuration_protected_settings) allowInsecureConnections = str(allowInsecureConnections).lower() == 'true' - if (not feSslCert or not sslKey) and not allowInsecureConnections: + if (not feSslCertFile or not feSslKeyFile) and not allowInsecureConnections: raise InvalidArgumentValueError( "Provide ssl certificate and key. " "Otherwise explicitly allow insecure connection by specifying " "'--configuration-settings allowInsecureConnections=true'") + feIsNodePort = _get_value_from_config_protected_config( + self.privateEndpointNodeport, configuration_settings, configuration_protected_settings) + feIsNodePort = str(feIsNodePort).lower() == 'true' feIsInternalLoadBalancer = _get_value_from_config_protected_config( - 'scoringFe.serviceType.internalLoadBalancer', configuration_settings, configuration_protected_settings) + self.privateEndpointILB, configuration_settings, configuration_protected_settings) feIsInternalLoadBalancer = str(feIsInternalLoadBalancer).lower() == 'true' - if feIsInternalLoadBalancer: + + if feIsNodePort and feIsInternalLoadBalancer: + raise MutuallyExclusiveArgumentError( + "Specify either privateEndpointNodeport=true or privateEndpointILB=true, but not both.") + if feIsNodePort: + configuration_settings['scoringFe.serviceType.nodePort'] = feIsNodePort + elif feIsInternalLoadBalancer: + configuration_settings['scoringFe.serviceType.internalLoadBalancer'] = feIsInternalLoadBalancer logger.warning( 'Internal load balancer only supported on AKS and AKS Engine Clusters.') + def __set_up_inference_ssl(self, configuration_settings, configuration_protected_settings): + allowInsecureConnections = _get_value_from_config_protected_config( + self.allowInsecureConnections, configuration_settings, configuration_protected_settings) + allowInsecureConnections = str(allowInsecureConnections).lower() == 'true' + if not allowInsecureConnections: + import base64 + feSslCertFile = configuration_protected_settings.get(self.sslCertPemFile) + feSslKeyFile = configuration_protected_settings.get(self.sslKeyPemFile) + with open(feSslCertFile) as f: + cert_data = f.read() + cert_data_bytes = cert_data.encode("ascii") + ssl_cert = base64.b64encode(cert_data_bytes).decode() + configuration_protected_settings['scoringFe.sslCert'] = ssl_cert + with open(feSslKeyFile) as f: + key_data = f.read() + key_data_bytes = key_data.encode("ascii") + ssl_key = base64.b64encode(key_data_bytes).decode() + configuration_protected_settings['scoringFe.sslKey'] = ssl_key + else: + logger.warning( + 'SSL is not enabled. Allowing insecure connections to the deployed services.') + def __create_required_resource( self, cmd, configuration_settings, configuration_protected_settings, subscription_id, resource_group_name, cluster_name, cluster_location): @@ -220,9 +274,8 @@ def __create_required_resource( configuration_settings[self.AZURE_LOG_ANALYTICS_CUSTOMER_ID_KEY] = ws_costumer_id configuration_protected_settings[self.AZURE_LOG_ANALYTICS_CONNECTION_STRING] = shared_key - if not configuration_settings.get( - self.RELAY_SERVER_CONNECTION_STRING) and not configuration_protected_settings.get( - self.RELAY_SERVER_CONNECTION_STRING): + if not configuration_settings.get(self.RELAY_SERVER_CONNECTION_STRING) and \ + not configuration_protected_settings.get(self.RELAY_SERVER_CONNECTION_STRING): logger.info('==== BEGIN RELAY CREATION ====') relay_connection_string, hc_resource_id, hc_name = _get_relay_connection_str( cmd, subscription_id, resource_group_name, cluster_name, cluster_location, self.RELAY_HC_AUTH_NAME) @@ -231,9 +284,8 @@ def __create_required_resource( configuration_settings[self.HC_RESOURCE_ID_KEY] = hc_resource_id configuration_settings[self.RELAY_HC_NAME_KEY] = hc_name - if not configuration_settings.get( - self.SERVICE_BUS_CONNECTION_STRING) and not configuration_protected_settings.get( - self.SERVICE_BUS_CONNECTION_STRING): + if not configuration_settings.get(self.SERVICE_BUS_CONNECTION_STRING) and \ + not configuration_protected_settings.get(self.SERVICE_BUS_CONNECTION_STRING): logger.info('==== BEGIN SERVICE BUS CREATION ====') topic_sub_mapping = { self.SERVICE_BUS_COMPUTE_STATE_TOPIC: self.SERVICE_BUS_COMPUTE_STATE_SUB, @@ -250,7 +302,7 @@ def __create_required_resource( def _get_valid_name(input_name: str, suffix_len: int, max_len: int) -> str: normalized_str = ''.join(filter(str.isalnum, input_name)) - assert len(normalized_str) > 0, "normalized name empty" + assert normalized_str, "normalized name empty" if len(normalized_str) <= max_len: return normalized_str @@ -265,22 +317,22 @@ def _get_valid_name(input_name: str, suffix_len: int, max_len: int) -> str: return new_name +# pylint: disable=broad-except def _lock_resource(cmd, lock_scope, lock_level='CanNotDelete'): lock_client: azure.mgmt.resource.locks.ManagementLockClient = get_mgmt_service_client( cmd.cli_ctx, azure.mgmt.resource.locks.ManagementLockClient) # put lock on relay resource - lock_object = ManagementLockObject(level=lock_level, notes='locked by amlk8s.') + lock_object = ManagementLockObject(level=lock_level, notes='locked by amlarc.') try: lock_client.management_locks.create_or_update_by_scope( - scope=lock_scope, lock_name='amlk8s-resource-lock', parameters=lock_object) - except: + scope=lock_scope, lock_name='amlarc-resource-lock', parameters=lock_object) + except Exception: # try to lock the resource if user has the owner privilege pass def _get_relay_connection_str( - cmd, subscription_id, resource_group_name, cluster_name, cluster_location, auth_rule_name) -> Tuple[ - str, str, str]: + cmd, subscription_id, resource_group_name, cluster_name, cluster_location, auth_rule_name) -> Tuple[str, str, str]: relay_client: azure.mgmt.relay.RelayManagementClient = get_mgmt_service_client( cmd.cli_ctx, azure.mgmt.relay.RelayManagementClient) @@ -335,7 +387,7 @@ def _get_service_bus_connection_string(cmd, subscription_id, resource_group_name location=cluster_location, sku=service_bus_sku, tags=resource_tag) - async_poller = service_bus_client.namespaces.create_or_update( + async_poller = service_bus_client.namespaces.begin_create_or_update( resource_group_name, service_bus_namespace_name, service_bus_namespace) while True: async_poller.result(15) @@ -368,8 +420,7 @@ def _get_service_bus_connection_string(cmd, subscription_id, resource_group_name def _get_log_analytics_ws_connection_string( - cmd, subscription_id, resource_group_name, cluster_name, cluster_location) -> Tuple[ - str, str]: + cmd, subscription_id, resource_group_name, cluster_name, cluster_location) -> Tuple[str, str]: log_analytics_ws_client: azure.mgmt.loganalytics.LogAnalyticsManagementClient = get_mgmt_service_client( cmd.cli_ctx, azure.mgmt.loganalytics.LogAnalyticsManagementClient) diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py b/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py new file mode 100644 index 00000000000..ed3e41891db --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py @@ -0,0 +1,61 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument + +from ..vendored_sdks.v2021_05_01_preview.models import ( + Extension, + ScopeCluster, + Scope, + ScopeNamespace +) + +from .PartnerExtensionModel import PartnerExtensionModel + + +class Cassandra(PartnerExtensionModel): + def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, + scope, auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file): + + """Default validations & defaults for Create + Must create and return a valid 'Extension' object. + + """ + ext_scope = None + if scope is not None: + if scope.lower() == 'cluster': + scope_cluster = ScopeCluster(release_namespace=release_namespace) + ext_scope = Scope(cluster=scope_cluster, namespace=None) + elif scope.lower() == 'namespace': + scope_namespace = ScopeNamespace(target_namespace=target_namespace) + ext_scope = Scope(namespace=scope_namespace, cluster=None) + + create_identity = True + extension_instance = Extension( + extension_type=extension_type, + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version, + scope=ext_scope, + configuration_settings=configuration_settings, + configuration_protected_settings=configuration_protected_settings, + ) + return extension_instance, name, create_identity + + def Update(self, extension, auto_upgrade_minor_version, release_train, version): + """Default validations & defaults for Update + Must create and return a valid 'Extension' object. + + """ + return Extension( + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version + ) + + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): + pass diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py index e84abd12801..9b19a338f6c 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py @@ -14,7 +14,6 @@ from azure.cli.core.commands import LongRunningOperation from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id from azure.cli.core.util import sdk_no_wait -from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id, is_valid_resource_id from ..vendored_sdks.v2021_05_01_preview.models import( @@ -38,7 +37,7 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t configuration_settings_file, configuration_protected_settings_file): """ExtensionType 'microsoft.azuremonitor.containers' specific validations & defaults for Create - Must create and return a valid 'ExtensionInstance' object. + Must create and return a valid 'Extension' object. """ # NOTE-1: Replace default scope creation with your customization! @@ -73,6 +72,20 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t ) return extension_instance, name, create_identity + def Update(self, extension, auto_upgrade_minor_version, release_train, version): + """ExtensionType 'microsoft.azuremonitor.containers' specific validations & defaults for Update + Must create and return a valid 'Extension' object. + + """ + return Extension( + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version + ) + + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): + pass + # Custom Validation Logic for Container Insights @@ -88,18 +101,15 @@ def _invoke_deployment(cmd, resource_group_name, deployment_name, template, para logger.info(json.dumps(template, indent=2)) logger.info('==== END TEMPLATE ====') - if cmd.supported_api_version(min_api='2019-10-01', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES): - deployment_temp = cmd.get_models('Deployment', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) - deployment = deployment_temp(properties=properties) - - if validate: - validation_poller = smc.validate(resource_group_name, deployment_name, deployment) + deployment_temp = cmd.get_models('Deployment', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) + deployment = deployment_temp(properties=properties) + if validate: + if cmd.supported_api_version(min_api='2019-10-01', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES): + validation_poller = smc.begin_validate(resource_group_name, deployment_name, deployment) return LongRunningOperation(cmd.cli_ctx)(validation_poller) - return sdk_no_wait(no_wait, smc.begin_create_or_update, resource_group_name, deployment_name, deployment) + return smc.validate(resource_group_name, deployment_name, deployment) - if validate: - return smc.validate(resource_group_name, deployment_name, properties) - return sdk_no_wait(no_wait, smc.begin_create_or_update, resource_group_name, deployment_name, properties) + return sdk_no_wait(no_wait, smc.begin_create_or_update, resource_group_name, deployment_name, deployment) def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, @@ -191,6 +201,9 @@ def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, "usgovvirginia": "usgovvirginia" } + from azure.core.exceptions import HttpResponseError + from azure.cli.core.profiles import ResourceType + cluster_location = '' resources = cf_resources(cmd.cli_ctx, subscription_id) @@ -199,7 +212,7 @@ def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, try: resource = resources.get_by_id(cluster_resource_id, '2020-01-01-preview') cluster_location = resource.location.lower() - except CloudError as ex: + except HttpResponseError as ex: raise ex cloud_name = cmd.cli_ctx.cloud.name.lower() @@ -251,23 +264,18 @@ def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, try: resource = resources.get_by_id(default_workspace_resource_id, '2015-11-01-preview') return resource.id - except CloudError as ex: + except HttpResponseError as ex: if ex.status_code != 404: raise ex else: - resource_groups.create_or_update(default_workspace_resource_group, { - 'location': workspace_region}) - - default_workspace_params = { - 'location': workspace_region, - 'properties': { - 'sku': { - 'name': 'standalone' - } - } - } - async_poller = resources.create_or_update_by_id(default_workspace_resource_id, '2015-11-01-preview', - default_workspace_params) + ResourceGroup = cmd.get_models('ResourceGroup', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) + resource_group = ResourceGroup(location=workspace_region) + resource_groups.create_or_update(default_workspace_resource_group, resource_group) + + GenericResource = cmd.get_models('GenericResource', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) + generic_resource = GenericResource(location=workspace_region, properties={'sku': {'name': 'standalone'}}) + async_poller = resources.begin_create_or_update_by_id(default_workspace_resource_id, '2015-11-01-preview', + generic_resource) ws_resource_id = '' while True: @@ -284,11 +292,12 @@ def _ensure_container_insights_for_monitoring(cmd, workspace_resource_id): parsed = parse_resource_id(workspace_resource_id) subscription_id, resource_group = parsed["subscription"], parsed["resource_group"] + from azure.core.exceptions import HttpResponseError resources = cf_resources(cmd.cli_ctx, subscription_id) try: resource = resources.get_by_id(workspace_resource_id, '2015-11-01-preview') location = resource.location - except CloudError as ex: + except HttpResponseError as ex: raise ex unix_time_in_millis = int( diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py index 07b2c9c5ae3..8518fb97a60 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py @@ -22,7 +22,7 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t configuration_settings_file, configuration_protected_settings_file): """Default validations & defaults for Create - Must create and return a valid 'ExtensionInstance' object. + Must create and return a valid 'Extension' object. """ ext_scope = None @@ -46,3 +46,16 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t ) return extension_instance, name, create_identity + def Update(self, extension, auto_upgrade_minor_version, release_train, version): + """Default validations & defaults for Update + Must create and return a valid 'Extension' object. + + """ + return Extension( + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version + ) + + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): + pass diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py b/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py new file mode 100644 index 00000000000..010a0b3c1fc --- /dev/null +++ b/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py @@ -0,0 +1,161 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-argument +# pylint: disable=redefined-outer-name +# pylint: disable=no-member + +from knack.log import get_logger + +from azure.cli.core.azclierror import InvalidArgumentValueError, RequiredArgumentMissingError +from azure.cli.core.commands.client_factory import get_subscription_id + +from packaging import version +import yaml + +from ..partner_extensions import PartnerExtensionModel + +from .PartnerExtensionModel import PartnerExtensionModel + +from ..vendored_sdks.v2021_05_01_preview .models import ( + Extension, + ScopeCluster, + Scope +) + +from .._client_factory import cf_resources + +logger = get_logger(__name__) + + +class OpenServiceMesh(PartnerExtensionModel): + CHART_NAME = "osm-arc" + CHART_LOCATION = "https://azure.github.io/osm-azure" + + def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, + scope, auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file): + + """ExtensionType 'microsoft.openservicemesh' specific validations & defaults for Create + Must create and return a valid 'Extension' object. + + """ + # NOTE-1: Replace default scope creation with your customization, if required + # Scope must always be cluster + ext_scope = None + if scope == 'namespace': + raise InvalidArgumentValueError("Invalid scope '{}'. This extension can be installed " + "only at 'cluster' scope.".format(scope)) + + scope_cluster = ScopeCluster(release_namespace=release_namespace) + ext_scope = Scope(cluster=scope_cluster, namespace=None) + + # version is a mandatory if release-train is staging or pilot + if version is None: + raise RequiredArgumentMissingError( + "A version must be provided for release-train {}.".format(release_train) + ) + # If the release-train is 'staging' or 'pilot' then auto-upgrade-minor-version MUST be set to False + if auto_upgrade_minor_version or auto_upgrade_minor_version is None: + auto_upgrade_minor_version = False + logger.warning("Setting auto-upgrade-minor-version to False since release-train is '%s'", release_train) + + # NOTE-2: Return a valid ExtensionInstance object, Instance name and flag for Identity + create_identity = False + + # _validate_tested_distro(cmd, resource_group_name, cluster_name, version) + + extension_instance = Extension( + extension_type=extension_type, + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version, + scope=ext_scope, + configuration_settings=configuration_settings, + configuration_protected_settings=configuration_protected_settings, + identity=None, + location="" + ) + return extension_instance, name, create_identity + + def Update(self, extension, auto_upgrade_minor_version, release_train, version): + """ExtensionType 'microsoft.openservicemesh' specific validations & defaults for Update + Must create and return a valid 'Extension' object. + + """ + # auto-upgrade-minor-version MUST be set to False if release_train is staging or pilot + if release_train.lower() in ['staging', 'pilot']: + if auto_upgrade_minor_version or auto_upgrade_minor_version is None: + auto_upgrade_minor_version = False + # Set version to None to always get the latest version - user cannot override + version = None + logger.warning("Setting auto-upgrade-minor-version to False since release-train is '%s'", release_train) + + return Extension( + auto_upgrade_minor_version=auto_upgrade_minor_version, + release_train=release_train, + version=version + ) + + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): + pass + + +# def _validate_tested_distro(cmd, cluster_resource_group_name, cluster_name, extension_version): + +# field_unavailable_error = '\"testedDistros\" field unavailable for version {0} of microsoft.openservicemesh, ' \ +# 'cannot determine if this Kubernetes distribution has been properly tested'.format(extension_version) + +# if version.parse(str(extension_version)) <= version.parse("0.8.3"): +# logger.warning(field_unavailable_error) +# return + +# subscription_id = get_subscription_id(cmd.cli_ctx) +# resources = cf_resources(cmd.cli_ctx, subscription_id) + +# cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Kubernetes' \ +# '/connectedClusters/{2}'.format(subscription_id, cluster_resource_group_name, cluster_name) + +# resource = resources.get_by_id(cluster_resource_id, '2020-01-01-preview') +# cluster_distro = resource.properties['distribution'].lower() + +# if cluster_distro == "general": +# logger.warning('Unable to determine if distro has been tested for microsoft.openservicemesh, ' +# 'kubernetes distro: \"general\"') +# return + +# tested_distros = _get_tested_distros(extension_version) + +# if tested_distros is None: +# logger.warning(field_unavailable_error) +# elif cluster_distro not in tested_distros.split(): +# logger.warning('Untested kubernetes distro for microsoft.openservicemesh, Kubernetes distro is %s', +# cluster_distro) + + +# def _get_tested_distros(chart_version): + +# try: +# chart_arc = ChartBuilder({ +# "name": OpenServiceMesh.CHART_NAME, +# "version": str(chart_version), +# "source": { +# "type": "repo", +# "location": OpenServiceMesh.CHART_LOCATION +# } +# }) +# except VersionError: +# raise InvalidArgumentValueError( +# "Invalid version '{}' for microsoft.openservicemesh".format(chart_version) +# ) + +# values = chart_arc.get_values() +# values_yaml = yaml.load(values.raw, Loader=yaml.FullLoader) + +# try: +# return values_yaml['OpenServiceMesh']['testedDistros'] +# except KeyError: +# return None diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py b/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py index a4ffa554e14..3c24c74c1ab 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py @@ -16,7 +16,11 @@ def Create(self, cmd, client, resource_group_name: str, cluster_name: str, name: configuration_protected_settings_file: str) -> Extension: pass - # @abstractmethod - # def Update(self, extension: ExtensionInstance, auto_upgrade_minor_version: bool, - # release_train: str, version: str) -> ExtensionInstanceUpdate: - # pass + @abstractmethod + def Update(self, extension: Extension, auto_upgrade_minor_version: bool, + release_train: str, version: str) -> Extension: + pass + + @abstractmethod + def Delete(self, client, resource_group_name: str, cluster_name: str, name: str, cluster_type: str): + pass diff --git a/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/cert_and_key_encoded.txt b/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/cert_and_key_encoded.txt new file mode 100644 index 00000000000..4c2cb46c832 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/cert_and_key_encoded.txt @@ -0,0 +1,2 @@ +dGVzdGNlcnQ= +dGVzdGtleQ== \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_cert.pem b/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_cert.pem new file mode 100644 index 00000000000..e7529e3fdea --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_cert.pem @@ -0,0 +1 @@ +testcert \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_key.pem b/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_key.pem new file mode 100644 index 00000000000..7ef00201c75 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_key.pem @@ -0,0 +1 @@ +testkey \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml b/src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml new file mode 100644 index 00000000000..7419d9c22bf --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml @@ -0,0 +1,370 @@ +interactions: +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - k8s-extension create + Connection: + - keep-alive + ParameterSetName: + - -g -n -c --cluster-type --extension-type --release-train --version + User-Agent: + - AZURECLI/2.24.2 azsdk-python-azure-mgmt-resource/18.0.0 Python/3.9.0 (Windows-10-10.0.19041-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.KubernetesConfiguration?api-version=2021-04-01 + response: + body: + string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.KubernetesConfiguration","namespace":"Microsoft.KubernetesConfiguration","authorizations":[{"applicationId":"c699bf69-fb1d-4eaf-999b-99e6b2ae4d85","roleDefinitionId":"90155430-a360-410f-af5d-89dc284d85c6"},{"applicationId":"03db181c-e9d3-4868-9097-f0b728327182","roleDefinitionId":"DE2ADB97-42D8-49C8-8FCF-DBB53EF936AC"},{"applicationId":"a0f92522-89de-4c5e-9a75-0044ccf66efd","roleDefinitionId":"b3429810-7d5c-420e-8605-cf280f3099f2"},{"applicationId":"bd9b7cd5-dac1-495f-b013-ac871e98fa5f","roleDefinitionId":"0d44c8f0-08b9-44d4-9f59-e51c83f95200"}],"resourceTypes":[{"resourceType":"sourceControlConfigurations","locations":["East + US","West Europe","West Central US","West US 2","South Central US","East US + 2","North Europe","UK South","Southeast Asia","Australia East","France Central","East + US 2 EUAP"],"apiVersions":["2021-03-01","2020-10-01-preview","2020-07-01-preview","2019-11-01-preview"],"defaultApiVersion":"2021-03-01","capabilities":"SupportsExtension"},{"resourceType":"extensions","locations":["East + US","West Europe","West Central US","West US 2","South Central US","East US + 2","North Europe","UK South","Southeast Asia","Australia East","France Central","East + US 2 EUAP"],"apiVersions":["2021-05-01-preview","2020-07-01-preview"],"capabilities":"SystemAssignedResourceIdentity, + SupportsExtension"},{"resourceType":"operations","locations":[],"apiVersions":["2021-05-01-preview","2021-03-01","2020-10-01-preview","2020-07-01-preview","2019-11-01-preview"],"capabilities":"None"}],"registrationState":"Registered","registrationPolicy":"RegistrationRequired"}' + headers: + cache-control: + - no-cache + content-length: + - '1654' + content-type: + - application/json; charset=utf-8 + date: + - Tue, 22 Jun 2021 23:19:11 GMT + expires: + - '-1' + pragma: + - no-cache + strict-transport-security: + - max-age=31536000; includeSubDomains + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + status: + code: 200 + message: OK +- request: + body: '{"location": "", "properties": {"extensionType": "microsoft.openservicemesh", + "autoUpgradeMinorVersion": false, "releaseTrain": "pilot", "version": "0.8.3", + "scope": {"cluster": {}}, "configurationSettings": {}, "configurationProtectedSettings": + {}}}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - k8s-extension create + Connection: + - keep-alive + Content-Length: + - '250' + Content-Type: + - application/json; charset=utf-8 + ParameterSetName: + - -g -n -c --cluster-type --extension-type --release-train --version + User-Agent: + - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 + azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 + accept-language: + - en-US + method: PUT + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview + response: + body: + string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"configurationSettings":{},"statuses":[],"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}}' + headers: + api-supported-versions: + - 2020-07-01-Preview, 2021-05-01-preview + cache-control: + - no-cache + content-length: + - '704' + content-type: + - application/json; charset=utf-8 + date: + - Tue, 22 Jun 2021 23:19:13 GMT + expires: + - '-1' + pragma: + - no-cache + server: + - openresty/1.15.8.2 + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding,Accept-Encoding + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-writes: + - '1199' + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - k8s-extension list + Connection: + - keep-alive + ParameterSetName: + - -c -g --cluster-type + User-Agent: + - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 + azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 + accept-language: + - en-US + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions?api-version=2020-07-01-preview + response: + body: + string: '{"value":[{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}},{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/hci22jan21","name":"hci22jan21","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"extensionType":"microsoft.azstackhci.operator","autoUpgradeMinorVersion":true,"releaseTrain":"stable","version":"1.0.0","scope":{"cluster":{"releaseNamespace":null}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-01-22T20:49:34.3336157+00:00","lastModifiedTime":"2021-01-22T20:49:34.3336249+00:00"}}],"nextLink":null}' + headers: + api-supported-versions: + - 2020-07-01-Preview, 2021-05-01-preview + cache-control: + - no-cache + content-length: + - '1337' + content-type: + - application/json; charset=utf-8 + date: + - Tue, 22 Jun 2021 23:19:14 GMT + expires: + - '-1' + pragma: + - no-cache + server: + - openresty/1.15.8.2 + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding,Accept-Encoding + x-content-type-options: + - nosniff + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - k8s-extension show + Connection: + - keep-alive + ParameterSetName: + - -c -g -n --cluster-type + User-Agent: + - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 + azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 + accept-language: + - en-US + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview + response: + body: + string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"configurationSettings":{},"statuses":[],"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}}' + headers: + api-supported-versions: + - 2020-07-01-Preview, 2021-05-01-preview + cache-control: + - no-cache + content-length: + - '704' + content-type: + - application/json; charset=utf-8 + date: + - Tue, 22 Jun 2021 23:19:15 GMT + expires: + - '-1' + pragma: + - no-cache + server: + - openresty/1.15.8.2 + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding,Accept-Encoding + x-content-type-options: + - nosniff + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - k8s-extension delete + Connection: + - keep-alive + ParameterSetName: + - -g -c -n --cluster-type -y + User-Agent: + - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 + azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 + accept-language: + - en-US + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview + response: + body: + string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"configurationSettings":{},"statuses":[],"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}}' + headers: + api-supported-versions: + - 2020-07-01-Preview, 2021-05-01-preview + cache-control: + - no-cache + content-length: + - '704' + content-type: + - application/json; charset=utf-8 + date: + - Tue, 22 Jun 2021 23:19:16 GMT + expires: + - '-1' + pragma: + - no-cache + server: + - openresty/1.15.8.2 + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding,Accept-Encoding + x-content-type-options: + - nosniff + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - k8s-extension delete + Connection: + - keep-alive + Content-Length: + - '0' + ParameterSetName: + - -g -c -n --cluster-type -y + User-Agent: + - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 + azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 + accept-language: + - en-US + method: DELETE + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview + response: + body: + string: '{"content":null,"statusCode":200,"headers":[],"version":"1.1","reasonPhrase":"OK","trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true}' + headers: + api-supported-versions: + - 2020-07-01-Preview, 2021-05-01-preview + cache-control: + - no-cache + content-length: + - '152' + content-type: + - application/json; charset=utf-8 + date: + - Tue, 22 Jun 2021 23:19:17 GMT + expires: + - '-1' + pragma: + - no-cache + server: + - openresty/1.15.8.2 + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-deletes: + - '14999' + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - k8s-extension list + Connection: + - keep-alive + ParameterSetName: + - -c -g --cluster-type + User-Agent: + - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 + azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 + accept-language: + - en-US + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions?api-version=2020-07-01-preview + response: + body: + string: '{"value":[{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/hci22jan21","name":"hci22jan21","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"extensionType":"microsoft.azstackhci.operator","autoUpgradeMinorVersion":true,"releaseTrain":"stable","version":"1.0.0","scope":{"cluster":{"releaseNamespace":null}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-01-22T20:49:34.3336157+00:00","lastModifiedTime":"2021-01-22T20:49:34.3336249+00:00"}}],"nextLink":null}' + headers: + api-supported-versions: + - 2020-07-01-Preview, 2021-05-01-preview + cache-control: + - no-cache + content-length: + - '673' + content-type: + - application/json; charset=utf-8 + date: + - Tue, 22 Jun 2021 23:19:19 GMT + expires: + - '-1' + pragma: + - no-cache + server: + - openresty/1.15.8.2 + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding,Accept-Encoding + x-content-type-options: + - nosniff + status: + code: 200 + message: OK +version: 1 diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_azureml_extension.py b/src/k8s-config/azext_k8s_config/tests/latest/test_azureml_extension.py new file mode 100644 index 00000000000..8ddf4dfaef2 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_azureml_extension.py @@ -0,0 +1,34 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +import os +import unittest + +from azext_k8s_extension.partner_extensions.AzureMLKubernetes import AzureMLKubernetes + + +TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + + +class TestAzureMlExtension(unittest.TestCase): + + def test_set_up_inference_ssl(self): + azremlk8sInstance = AzureMLKubernetes() + config = {'allowInsecureConnections': 'false'} + # read and encode dummy cert and key + sslKeyPemFile = os.path.join(TEST_DIR, 'data', 'azure_ml', 'test_key.pem') + sslCertPemFile = os.path.join(TEST_DIR, 'data', 'azure_ml', 'test_cert.pem') + protected_config = {'sslKeyPemFile': sslKeyPemFile, 'sslCertPemFile': sslCertPemFile} + azremlk8sInstance._AzureMLKubernetes__set_up_inference_ssl(config, protected_config) + self.assertTrue('scoringFe.sslCert' in protected_config) + self.assertTrue('scoringFe.sslKey' in protected_config) + encoded_cert_and_key_file = os.path.join(TEST_DIR, 'data', 'azure_ml', 'cert_and_key_encoded.txt') + with open(encoded_cert_and_key_file, "r") as text_file: + cert = text_file.readline().rstrip() + assert cert == protected_config['scoringFe.sslCert'] + key = text_file.readline() + assert key == protected_config['scoringFe.sslKey'] diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py new file mode 100644 index 00000000000..53db4ce2c2d --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py @@ -0,0 +1,69 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=line-too-long + +import os +from azure.cli.testsdk import (ScenarioTest, record_only) + + +TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + + +class K8sExtensionScenarioTest(ScenarioTest): + @record_only() + def test_k8s_extension(self): + resource_type = 'microsoft.openservicemesh' + self.kwargs.update({ + 'name': 'openservicemesh', + 'rg': 'nanthirg0923', + 'cluster_name': 'nanthicluster0923', + 'cluster_type': 'connectedClusters', + 'extension_type': resource_type, + 'release_train': 'pilot', + 'version': '0.8.3' + }) + + self.cmd('k8s-extension create -g {rg} -n {name} -c {cluster_name} --cluster-type {cluster_type} ' + '--extension-type {extension_type} --release-train {release_train} --version {version}', + checks=[ + self.check('name', '{name}'), + self.check('releaseTrain', '{release_train}'), + self.check('version', '{version}'), + self.check('resourceGroup', '{rg}'), + self.check('extensionType', '{extension_type}') + ] + ) + + # Update is disabled for now + # self.cmd('k8s-extension update -g {rg} -n {name} --tags foo=boo', checks=[ + # self.check('tags.foo', 'boo') + # ]) + + installed_exts = self.cmd('k8s-extension list -c {cluster_name} -g {rg} --cluster-type {cluster_type}').get_output_in_json() + found_extension = False + for item in installed_exts: + if item['extensionType'] == resource_type: + found_extension = True + break + self.assertTrue(found_extension) + + self.cmd('k8s-extension show -c {cluster_name} -g {rg} -n {name} --cluster-type {cluster_type}', checks=[ + self.check('name', '{name}'), + self.check('releaseTrain', '{release_train}'), + self.check('version', '{version}'), + self.check('resourceGroup', '{rg}'), + self.check('extensionType', '{extension_type}') + ]) + + self.cmd('k8s-extension delete -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type} -y') + + installed_exts = self.cmd('k8s-extension list -c {cluster_name} -g {rg} --cluster-type {cluster_type}').get_output_in_json() + found_extension = False + for item in installed_exts: + if item['extensionType'] == resource_type: + found_extension = True + break + self.assertFalse(found_extension) diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_open_service_mesh.py b/src/k8s-config/azext_k8s_config/tests/latest/test_open_service_mesh.py new file mode 100644 index 00000000000..61b774045ce --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_open_service_mesh.py @@ -0,0 +1,23 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +import os +import unittest + +from azure.cli.core.azclierror import InvalidArgumentValueError +# from azext_k8s_extension.partner_extensions.OpenServiceMesh import _get_tested_distros + +TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + +class TestOpenServiceMesh(unittest.TestCase): + def test_bad_osm_arc_version(self): + # version = "0.7.1" + # err = "Invalid version \'" + str(version) + "\' for microsoft.openservicemesh" + # with self.assertRaises(InvalidArgumentValueError) as argError: + # _get_tested_distros(version) + # self.assertEqual(str(argError.exception), err) + pass From 238c86bbed68f73debd3d31c4175109bf104e8a3 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 22 Jul 2021 12:04:02 -0700 Subject: [PATCH 26/61] Add k8s-config testing --- k8s-custom-pipelines.yml | 30 +++++++++---------- src/k8s-config/azext_k8s_config/_help.py | 18 +++++------ src/k8s-config/azext_k8s_config/commands.py | 2 +- .../SourceControlConfigurationProvider.py | 2 +- testing/Test.ps1 | 12 +++++++- .../Configuration.HTTPS.Tests.ps1 | 10 +++---- .../Configuration.HelmOperator.Tests.ps1 | 22 +++++++------- .../Configuration.PrivateKey.Tests.ps1 | 19 ++++++------ .../configurations/Configuration.Tests.ps1 | 18 +++++------ .../extensions/public/AzureDefender.Tests.ps1 | 18 +++++------ .../public/AzureMLKubernetes.Tests.ps1 | 18 +++++------ .../extensions/public/AzureMonitor.Tests.ps1 | 18 +++++------ 12 files changed, 98 insertions(+), 89 deletions(-) diff --git a/k8s-custom-pipelines.yml b/k8s-custom-pipelines.yml index 940770361d9..f93c4a8d42c 100644 --- a/k8s-custom-pipelines.yml +++ b/k8s-custom-pipelines.yml @@ -2,11 +2,11 @@ trigger: batch: true branches: include: - - k8s-configuration + - k8s-config pr: branches: include: - - k8s-configuration + - k8s-config stages: - stage: BuildTestPublishExtension @@ -14,16 +14,16 @@ stages: variables: TEST_PATH: $(Agent.BuildDirectory)/s/testing CLI_REPO_PATH: $(Agent.BuildDirectory)/s - EXTENSION_NAME: "k8s-configuration" - EXTENSION_FILE_NAME: "k8s_configuration" + EXTENSION_NAME: "k8s-config" + EXTENSION_FILE_NAME: "k8s_config" SUBSCRIPTION_ID: "15c06b1b-01d6-407b-bb21-740b8617dea3" RESOURCE_GROUP: "K8sPartnerExtensionTest" - BASE_CLUSTER_NAME: "k8s-configuration-cluster" + BASE_CLUSTER_NAME: "k8s-config-cluster" jobs: - job: K8sConfigurationTestSuite displayName: "Run the Test Suite" pool: - vmImage: 'ubuntu-16.04' + vmImage: 'ubuntu-latest' steps: - checkout: self - bash: | @@ -82,7 +82,7 @@ stages: --arg AKS_CLUSTER_NAME "$AKS_CLUSTER_NAME" \ --arg ARC_CLUSTER_NAME "$ARC_CLUSTER_NAME" \ --arg K8S_CONFIG_VERSION "$K8S_CONFIG_VERSION" \ - '{subscriptionId: $SUB_ID, resourceGroup: $RG, aksClusterName: $AKS_CLUSTER_NAME, arcClusterName: $ARC_CLUSTER_NAME, extensionVersion: {"k8s-configuration": $K8S_CONFIG_VERSION, connectedk8s: "1.0.0"}}') + '{subscriptionId: $SUB_ID, resourceGroup: $RG, aksClusterName: $AKS_CLUSTER_NAME, arcClusterName: $ARC_CLUSTER_NAME, extensionVersion: {"k8s-config": $K8S_CONFIG_VERSION, connectedk8s: "1.0.0"}}') echo $JSON_STRING > settings.json cat settings.json workingDirectory: $(TEST_PATH) @@ -90,7 +90,7 @@ stages: - bash : | echo "Downloading the kind script" - curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.9.0/kind-linux-amd64 + curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.11.1/kind-linux-amd64 chmod +x ./kind ./kind create cluster displayName: "Create and Start the Kind cluster" @@ -112,7 +112,7 @@ stages: scriptType: pscore scriptLocation: inlineScript inlineScript: | - .\Test.ps1 -Type k8s-configuration -CI + .\Test.ps1 -Type k8s-config -CI workingDirectory: $(TEST_PATH) continueOnError: true @@ -136,7 +136,7 @@ stages: - job: BuildPublishExtension pool: - vmImage: 'ubuntu-16.04' + vmImage: 'ubuntu-latest' displayName: "Build and Publish the Extension Artifact" variables: CLI_REPO_PATH: $(Agent.BuildDirectory)/s @@ -177,7 +177,7 @@ stages: - job: CheckLicenseHeader displayName: "Check License" pool: - vmImage: 'ubuntu-16.04' + vmImage: 'ubuntu-latest' steps: - task: UsePythonVersion@0 displayName: 'Use Python 3.6' @@ -208,7 +208,7 @@ stages: - job: StaticAnalysis displayName: "Static Analysis" pool: - vmImage: 'ubuntu-16.04' + vmImage: 'ubuntu-latest' steps: - task: UsePythonVersion@0 displayName: 'Use Python 3.6' @@ -222,7 +222,7 @@ stages: - job: IndexVerify displayName: "Verify Extensions Index" pool: - vmImage: 'ubuntu-16.04' + vmImage: 'ubuntu-latest' steps: - task: UsePythonVersion@0 displayName: 'Use Python 3.7' @@ -239,7 +239,7 @@ stages: - job: SourceTests displayName: "Integration Tests, Build Tests" pool: - vmImage: 'ubuntu-16.04' + vmImage: 'ubuntu-latest' strategy: matrix: Python36: @@ -262,7 +262,7 @@ stages: - job: LintModifiedExtensions displayName: "CLI Linter on Modified Extensions" pool: - vmImage: 'ubuntu-16.04' + vmImage: 'ubuntu-latest' steps: - task: UsePythonVersion@0 displayName: 'Use Python 3.6' diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 3a464114bc3..32b1959a60e 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -11,18 +11,18 @@ short-summary: Commands to manage resources from Microsoft.KubernetesConfiguration. """ -helps['k8s-config flux-v1'] = """ +helps['k8s-config fluxv1'] = """ type: group short-summary: Commands to manage Flux V1 Kubernetes configurations. """ -helps['k8s-config flux-v1 create'] = """ +helps['k8s-config fluxv1 create'] = """ type: command short-summary: Create a Kubernetes configuration. examples: - name: Create a Kubernetes configuration text: |- - az k8s-config flux-v1 create --resource-group MyResourceGroup --cluster-name MyClusterName \\ + az k8s-config fluxv1 create --resource-group MyResourceGroup --cluster-name MyClusterName \\ --cluster-type connectedClusters --name MyGitConfig --operator-instance-name OperatorInst01 \\ --operator-namespace OperatorNamespace01 --operator-type flux --operator-params "'--git-readonly'" \\ --repository-url git://github.com/fluxHowTo/flux-get-started --enable-helm-operator \\ @@ -31,33 +31,33 @@ --ssh-known-hosts '' --ssh-known-hosts-file '' """ -helps['k8s-config flux-v1 list'] = """ +helps['k8s-config fluxv1 list'] = """ type: command short-summary: List Kubernetes configurations. examples: - name: List all Kubernetes configurations of a cluster text: |- - az k8s-config flux-v1 list --resource-group MyResourceGroup --cluster-name MyClusterName \\ + az k8s-config fluxv1 list --resource-group MyResourceGroup --cluster-name MyClusterName \\ --cluster-type connectedClusters """ -helps['k8s-config flux-v1 delete'] = """ +helps['k8s-config fluxv1 delete'] = """ type: command short-summary: Delete a Kubernetes configuration. examples: - name: Delete a Kubernetes configuration text: |- - az k8s-config flux-v1 delete --resource-group MyResourceGroup --cluster-name MyClusterName \\ + az k8s-config fluxv1 delete --resource-group MyResourceGroup --cluster-name MyClusterName \\ --cluster-type connectedClusters --name MyConfigurationName """ -helps['k8s-config flux-v1 show'] = """ +helps['k8s-config fluxv1 show'] = """ type: command short-summary: Show details of a Kubernetes configuration. examples: - name: Show a Kubernetes configuration text: |- - az k8s-config flux-v1 show --resource-group MyResourceGroup --cluster-name MyClusterName \\ + az k8s-config fluxv1 show --resource-group MyResourceGroup --cluster-name MyClusterName \\ --cluster-type connectedClusters --name MyConfigurationName """ diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index a9d3c39c6ec..b89729f8867 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -50,7 +50,7 @@ def load_command_table(self, _): g.custom_command('show', 'extension_show', table_transformer=extension_show_table_format) g.custom_command('delete', 'extension_delete', confirmation=True) - with self.command_group('k8s-config flux-v1', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client, deprecate_info=self.deprecate(redirect='k8s-config flux')) as g: + with self.command_group('k8s-config fluxv1', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client, deprecate_info=self.deprecate(redirect='k8s-config flux')) as g: g.custom_command('create', 'sourcecontrol_create') g.custom_command('list', 'sourcecontrol_list', table_transformer=sourcecontrol_list_table_format) g.custom_show_command('show', 'sourcecontrol_show', table_transformer=sourcecontrol_show_table_format) diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py index 8c421f1803c..5987d8d85d8 100644 --- a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py @@ -51,7 +51,7 @@ def list(self, resource_group_name, cluster_type, cluster_name): def delete(self, resource_group_name, cluster_type, cluster_name, name): cluster_rp = get_cluster_rp(cluster_type) - return self.client.delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) # pylint: disable=too-many-locals def create(self, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, diff --git a/testing/Test.ps1 b/testing/Test.ps1 index 06c089f6f52..1fdc5e4db0d 100644 --- a/testing/Test.ps1 +++ b/testing/Test.ps1 @@ -5,7 +5,7 @@ param ( [switch] $OnlyPublicTests, [Parameter(Mandatory=$True)] - [ValidateSet('k8s-extension','k8s-configuration', 'k8s-extension-private')] + [ValidateSet('k8s-extension', 'k8s-configuration', 'k8s-extension-private', 'k8s-config')] [string]$Type ) @@ -65,6 +65,16 @@ if ($Type -eq 'k8s-extension') { az extension add --source ./bin/k8s_configuration-$k8sConfigurationVersion-py3-none-any.whl } $testFilePath = "$PSScriptRoot/test/configurations" +} elseif ($Type -eq 'k8s-config') { + $k8sConfigVersion = $ENVCONFIG.extensionVersion.'k8s-config' + if (!$SkipInstall) { + Write-Host "Removing the old k8s-config extension..." + az extension remove -n k8s-config + Write-Host "Installing k8s-config version $k8sConfigVersion..." + az extension add --source ./bin/k8s_config-$k8sConfigVersion-py3-none-any.whl + } + $Env:K8sExtensionName = "k8s-config" + $testFilePath = "$PSScriptRoot/test" } if ($CI) { diff --git a/testing/test/configurations/Configuration.HTTPS.Tests.ps1 b/testing/test/configurations/Configuration.HTTPS.Tests.ps1 index a2dee2b348f..38d53224cf4 100644 --- a/testing/test/configurations/Configuration.HTTPS.Tests.ps1 +++ b/testing/test/configurations/Configuration.HTTPS.Tests.ps1 @@ -9,7 +9,7 @@ Describe 'Source Control Configuration (HTTPS) Testing' { } It 'Creates a configuration with https user and https key on the cluster' { - $output = az k8s-configuration create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "https://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --https-user $dummyValue --https-key $dummyValue --operator-namespace $configurationName + $output = az k8s-config fluxv1 create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "https://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --https-user $dummyValue --https-key $dummyValue --operator-namespace $configurationName $? | Should -BeTrue # Loop and retry until the configuration installs and helm pod comes up @@ -30,7 +30,7 @@ Describe 'Source Control Configuration (HTTPS) Testing' { } It "Lists the configurations on the cluster" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue $configExists = $output | ConvertFrom-Json | Where-Object { $_.id -Match $configurationName } @@ -38,16 +38,16 @@ Describe 'Source Control Configuration (HTTPS) Testing' { } It "Deletes the configuration from the cluster" { - az k8s-configuration delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + az k8s-config fluxv1 delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeTrue # Configuration should be removed from the resource model - az k8s-configuration show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + az k8s-config fluxv1 show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeFalse } It "Performs another list after the delete" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $configExists = $output | ConvertFrom-Json | Where-Object { $_.id -Match $configurationName } $configExists | Should -BeNullOrEmpty } diff --git a/testing/test/configurations/Configuration.HelmOperator.Tests.ps1 b/testing/test/configurations/Configuration.HelmOperator.Tests.ps1 index 8b89ba24c58..06059ec6ea0 100644 --- a/testing/test/configurations/Configuration.HelmOperator.Tests.ps1 +++ b/testing/test/configurations/Configuration.HelmOperator.Tests.ps1 @@ -9,7 +9,7 @@ Describe 'Source Control Configuration (Helm Operator Properties) Testing' { } It 'Creates a configuration with helm enabled on the cluster' { - $output = az k8s-configuration create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "https://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --enable-helm-operator --operator-namespace $configurationName --helm-operator-params "--set helm.versions=v3" + $output = az k8s-config fluxv1 create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "https://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --enable-helm-operator --operator-namespace $configurationName --helm-operator-params "--set helm.versions=v3" $? | Should -BeTrue # Loop and retry until the configuration installs and helm pod comes up @@ -30,10 +30,10 @@ Describe 'Source Control Configuration (Helm Operator Properties) Testing' { It "Updates the helm operator params and performs a show" { Set-ItResult -Skipped -Because "Update is not a valid scenario for now" - az k8s-configuration update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName --helm-operator-params $customOperatorParams + az k8s-config fluxv1 update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName --helm-operator-params $customOperatorParams $? | Should -BeTrue - $output = az k8s-configuration show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + $output = az k8s-config fluxv1 show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeTrue $configData = $output | ConvertFrom-Json | Where-Object { $_.id -Match $configurationName } @@ -58,10 +58,10 @@ Describe 'Source Control Configuration (Helm Operator Properties) Testing' { It "Updates the helm operator chart version and performs a show" { Set-ItResult -Skipped -Because "Update is not a valid scenario for now" - az k8s-configuration update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName --helm-operator-chart-version $customChartVersion + az k8s-config fluxv1 update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName --helm-operator-chart-version $customChartVersion $? | Should -BeTrue - $output = az k8s-configuration show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + $output = az k8s-config fluxv1 show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeTrue # Check that the helmOperatorProperties chartValues didn't change @@ -88,10 +88,10 @@ Describe 'Source Control Configuration (Helm Operator Properties) Testing' { It "Disables the helm operator on the cluster" { Set-ItResult -Skipped -Because "Update is not a valid scenario for now" - az k8s-configuration update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName --enable-helm-operator=false + az k8s-config fluxv1 update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName --enable-helm-operator=false $? | Should -BeTrue - $output = az k8s-configuration show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + $output = az k8s-config fluxv1 show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeTrue $helmOperatorEnabled = ($output | ConvertFrom-Json).enableHelmOperator @@ -113,7 +113,7 @@ Describe 'Source Control Configuration (Helm Operator Properties) Testing' { } It "Lists the configurations on the cluster" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue $configExists = $output | ConvertFrom-Json | Where-Object { $_.id -Match $configurationName } @@ -121,16 +121,16 @@ Describe 'Source Control Configuration (Helm Operator Properties) Testing' { } It "Deletes the configuration from the cluster" { - az k8s-configuration delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + az k8s-config fluxv1 delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeTrue # Configuration should be removed from the resource model - az k8s-configuration show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + az k8s-config fluxv1 show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeFalse } It "Performs another list after the delete" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $configExists = $output | ConvertFrom-Json | Where-Object { $_.id -Match $configurationName } $configExists | Should -BeNullOrEmpty } diff --git a/testing/test/configurations/Configuration.PrivateKey.Tests.ps1 b/testing/test/configurations/Configuration.PrivateKey.Tests.ps1 index 4bf86d52012..f4aaadc225a 100644 --- a/testing/test/configurations/Configuration.PrivateKey.Tests.ps1 +++ b/testing/test/configurations/Configuration.PrivateKey.Tests.ps1 @@ -8,7 +8,7 @@ Describe 'Source Control Configuration (SSH Configs) Testing' { $ECDSA_KEYPATH = "$TMP_DIRECTORY\ecdsa.private" $ED25519_KEYPATH = "$TMP_DIRECTORY\ed25519.private" - $KEY_ARR = [System.Tuple]::Create("rsa", $RSA_KEYPATH), [System.Tuple]::Create("dsa", $DSA_KEYPATH), [System.Tuple]::Create("ecdsa", $ECDSA_KEYPATH), [System.Tuple]::Create("ed25519", $ED25519_KEYPATH) + $KEY_ARR = [System.Tuple]::Create("rsa", $RSA_KEYPATH), [System.Tuple]::Create("ecdsa", $ECDSA_KEYPATH), [System.Tuple]::Create("ed25519", $ED25519_KEYPATH) foreach ($keyTuple in $KEY_ARR) { # Automattically say yes to overwrite with ssh-keygen Write-Output "y" | ssh-keygen -t $keyTuple.Item1 -f $keyTuple.Item2 -P """" @@ -18,16 +18,15 @@ Describe 'Source Control Configuration (SSH Configs) Testing' { $HTTP_GIT_URL = "https://github.com/Azure/arc-k8s-demo" $configDataRSA = [System.Tuple]::Create("rsa-config", $RSA_KEYPATH) - $configDataDSA = [System.Tuple]::Create("dsa-config", $DSA_KEYPATH) $configDataECDSA = [System.Tuple]::Create("ecdsa-config", $ECDSA_KEYPATH) $configDataED25519 = [System.Tuple]::Create("ed25519-config", $ED25519_KEYPATH) - $CONFIG_ARR = $configDataRSA, $configDataDSA, $configDataECDSA, $configDataED25519 + $CONFIG_ARR = $configDataRSA, $configDataECDSA, $configDataED25519 } It 'Creates a configuration with each type of ssh private key' { foreach($configData in $CONFIG_ARR) { - az k8s-configuration create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u $SSH_GIT_URL -n $configData.Item1 --scope cluster --operator-namespace $configData.Item1 --ssh-private-key-file $configData.Item2 + az k8s-config fluxv1 create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u $SSH_GIT_URL -n $configData.Item1 --scope cluster --operator-namespace $configData.Item1 --ssh-private-key-file $configData.Item2 $? | Should -BeTrue } @@ -44,17 +43,17 @@ Describe 'Source Control Configuration (SSH Configs) Testing' { } Start-Sleep -Seconds 10 $n += 1 - } while ($n -le 30 -And $readyConfigs -ne 4) + } while ($n -le 30 -And $readyConfigs -ne 3) $n | Should -BeLessOrEqual 30 } It 'Fails when trying to create a configuration with ssh url and https auth values' { - az k8s-configuration create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u $HTTP_GIT_URL -n "config-should-fail" --scope cluster --operator-namespace "config-should-fail" --ssh-private-key-file $RSA_KEYPATH + az k8s-config fluxv1 create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u $HTTP_GIT_URL -n "config-should-fail" --scope cluster --operator-namespace "config-should-fail" --ssh-private-key-file $RSA_KEYPATH $? | Should -BeFalse } It "Lists the configurations on the cluster" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue foreach ($configData in $CONFIG_ARR) { @@ -65,17 +64,17 @@ Describe 'Source Control Configuration (SSH Configs) Testing' { It "Deletes the configuration from the cluster" { foreach ($configData in $CONFIG_ARR) { - az k8s-configuration delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configData.Item1 + az k8s-config fluxv1 delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configData.Item1 $? | Should -BeTrue # Configuration should be removed from the resource model - az k8s-configuration show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configData.Item1 + az k8s-config fluxv1 show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configData.Item1 $? | Should -BeFalse } } It "Performs another list after the delete" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue foreach ($configData in $CONFIG_ARR) { diff --git a/testing/test/configurations/Configuration.Tests.ps1 b/testing/test/configurations/Configuration.Tests.ps1 index 23a8170fd44..e4b5a86e543 100644 --- a/testing/test/configurations/Configuration.Tests.ps1 +++ b/testing/test/configurations/Configuration.Tests.ps1 @@ -6,7 +6,7 @@ Describe 'Basic Source Control Configuration Testing' { } It 'Creates a configuration and checks that it onboards correctly' { - az k8s-configuration create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "https://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --enable-helm-operator=false --operator-namespace $configurationName + az k8s-config fluxv1 create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "https://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --enable-helm-operator=false --operator-namespace $configurationName $? | Should -BeTrue # Loop and retry until the configuration installs @@ -23,7 +23,7 @@ Describe 'Basic Source Control Configuration Testing' { } It "Performs a show on the configuration" { - $output = az k8s-configuration show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName + $output = az k8s-config fluxv1 show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -n $configurationName $? | Should -BeTrue $output | Should -Not -BeNullOrEmpty } @@ -31,10 +31,10 @@ Describe 'Basic Source Control Configuration Testing' { It "Runs an update on the configuration on the cluster" { Set-ItResult -Skipped -Because "Update is not a valid scenario for now" - az k8s-configuration update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName --enable-helm-operator + az k8s-config fluxv1 update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName --enable-helm-operator $? | Should -BeTrue - $output = az k8s-configuration show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + $output = az k8s-config fluxv1 show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeTrue $helmOperatorEnabled = ($output | ConvertFrom-Json).enableHelmOperator @@ -56,12 +56,12 @@ Describe 'Basic Source Control Configuration Testing' { } It "Performs a re-PUT of the configuration on the cluster, with HTTPS in caps" { - az k8s-configuration create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "HTTPS://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --enable-helm-operator=false --operator-namespace $configurationName + az k8s-config fluxv1 create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type "connectedClusters" -u "HTTPS://github.com/Azure/arc-k8s-demo" -n $configurationName --scope cluster --enable-helm-operator=false --operator-namespace $configurationName $? | Should -BeTrue } It "Lists the configurations on the cluster" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue $configExists = $output | ConvertFrom-Json | Where-Object { $_.id -Match $configurationName } @@ -69,16 +69,16 @@ Describe 'Basic Source Control Configuration Testing' { } It "Deletes the configuration from the cluster" { - az k8s-configuration delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + az k8s-config fluxv1 delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeTrue # Configuration should be removed from the resource model - az k8s-configuration show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName + az k8s-config fluxv1 show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $configurationName $? | Should -BeFalse } It "Performs another list after the delete" { - $output = az k8s-configuration list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az k8s-config fluxv1 list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $configExists = $output | ConvertFrom-Json | Where-Object { $_.id -Match $configurationName } $configExists | Should -BeNullOrEmpty } diff --git a/testing/test/extensions/public/AzureDefender.Tests.ps1 b/testing/test/extensions/public/AzureDefender.Tests.ps1 index 2d199e31638..3d7c654dd4e 100644 --- a/testing/test/extensions/public/AzureDefender.Tests.ps1 +++ b/testing/test/extensions/public/AzureDefender.Tests.ps1 @@ -9,10 +9,10 @@ Describe 'Azure Defender Testing' { } It 'Creates the extension and checks that it onboards correctly' { - $output = az $Env:K8sExtensionName create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType -n $extensionName + $output = az $Env:K8sExtensionName extension create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType -n $extensionName $? | Should -BeTrue - $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue $isAutoUpgradeMinorVersion = ($output | ConvertFrom-Json).autoUpgradeMinorVersion @@ -33,7 +33,7 @@ Describe 'Azure Defender Testing' { } It "Performs a show on the extension" { - $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue $output | Should -Not -BeNullOrEmpty } @@ -41,10 +41,10 @@ Describe 'Azure Defender Testing' { It "Runs an update on the extension on the cluster" { Set-ItResult -Skipped -Because "Update is not a valid scenario for now" - # az $Env:K8sExtensionName update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName --auto-upgrade-minor-version false + # az $Env:K8sExtensionName extension update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName --auto-upgrade-minor-version false # $? | Should -BeTrue - # $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + # $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName # $? | Should -BeTrue # $isAutoUpgradeMinorVersion = ($output | ConvertFrom-Json).autoUpgradeMinorVersion @@ -69,7 +69,7 @@ Describe 'Azure Defender Testing' { } It "Lists the extensions on the cluster" { - $output = az $Env:K8sExtensionName list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionType } @@ -77,16 +77,16 @@ Describe 'Azure Defender Testing' { } It "Deletes the extension from the cluster" { - az $Env:K8sExtensionName delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + az $Env:K8sExtensionName extension delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue # Extension should not be found on the cluster - az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeFalse } It "Performs another list after the delete" { - $output = az $Env:K8sExtensionName list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionName } $extensionExists | Should -BeNullOrEmpty } diff --git a/testing/test/extensions/public/AzureMLKubernetes.Tests.ps1 b/testing/test/extensions/public/AzureMLKubernetes.Tests.ps1 index a434544da12..85caea480c7 100644 --- a/testing/test/extensions/public/AzureMLKubernetes.Tests.ps1 +++ b/testing/test/extensions/public/AzureMLKubernetes.Tests.ps1 @@ -10,10 +10,10 @@ Describe 'AzureML Kubernetes Testing' { } It 'Creates the extension and checks that it onboards correctly' { - $output = az k8s-extension create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType --name $extensionName --release-train preview --config enableTraining=true allowInsecureConnections=true + $output = az $Env:K8sExtensionName extension create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType --name $extensionName --release-train preview --config enableTraining=true allowInsecureConnections=true $? | Should -BeTrue - $output = az k8s-extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName + $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName $? | Should -BeTrue $isAutoUpgradeMinorVersion = ($output | ConvertFrom-Json).autoUpgradeMinorVersion @@ -37,17 +37,17 @@ Describe 'AzureML Kubernetes Testing' { } It "Performs a show on the extension" { - $output = az k8s-extension show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName + $output = az $Env:K8sExtensionName extension show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName $? | Should -BeTrue $output | Should -Not -BeNullOrEmpty } It "Runs an update on the extension on the cluster" { Set-ItResult -Skipped -Because "Update is not a valid scenario for now" - az k8s-extension update --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName --auto-upgrade-minor-version false + az $Env:K8sExtensionName extension update --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName --auto-upgrade-minor-version false $? | Should -BeTrue - $output = az k8s-extension show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName + $output = az $Env:K8sExtensionName extension show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName $? | Should -BeTrue $isAutoUpgradeMinorVersion = ($output | ConvertFrom-Json).autoUpgradeMinorVersion @@ -70,7 +70,7 @@ Describe 'AzureML Kubernetes Testing' { } It "Lists the extensions on the cluster" { - $output = az k8s-extension list --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionType } @@ -78,16 +78,16 @@ Describe 'AzureML Kubernetes Testing' { } It "Deletes the extension from the cluster" { - az k8s-extension delete --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName + az $Env:K8sExtensionName extension delete --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName $? | Should -BeTrue # Extension should not be found on the cluster - az k8s-extension show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName + az $Env:K8sExtensionName extension show --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --name $extensionName $? | Should -BeFalse } It "Performs another list after the delete" { - $output = az k8s-extension list --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list --cluster-name $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionName } $extensionExists | Should -BeNullOrEmpty } diff --git a/testing/test/extensions/public/AzureMonitor.Tests.ps1 b/testing/test/extensions/public/AzureMonitor.Tests.ps1 index c9baa2d0e48..11553c30c23 100644 --- a/testing/test/extensions/public/AzureMonitor.Tests.ps1 +++ b/testing/test/extensions/public/AzureMonitor.Tests.ps1 @@ -10,10 +10,10 @@ Describe 'Azure Monitor Testing' { } It 'Creates the extension and checks that it onboards correctly' { - $output = az $Env:K8sExtensionName create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType -n $extensionName + $output = az $Env:K8sExtensionName extension create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType -n $extensionName $? | Should -BeTrue - $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue $isAutoUpgradeMinorVersion = ($output | ConvertFrom-Json).autoUpgradeMinorVersion @@ -35,7 +35,7 @@ Describe 'Azure Monitor Testing' { } It "Performs a show on the extension" { - $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue $output | Should -Not -BeNullOrEmpty } @@ -43,10 +43,10 @@ Describe 'Azure Monitor Testing' { It "Runs an update on the extension on the cluster" { Set-ItResult -Skipped -Because "Update is not a valid scenario for now" - # az $Env:K8sExtensionName update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName --auto-upgrade-minor-version false + # az $Env:K8sExtensionName extension update -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName --auto-upgrade-minor-version false # $? | Should -BeTrue - # $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + # $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName # $? | Should -BeTrue # $isAutoUpgradeMinorVersion = ($output | ConvertFrom-Json).autoUpgradeMinorVersion @@ -71,7 +71,7 @@ Describe 'Azure Monitor Testing' { } It "Lists the extensions on the cluster" { - $output = az $Env:K8sExtensionName list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionType } @@ -79,16 +79,16 @@ Describe 'Azure Monitor Testing' { } It "Deletes the extension from the cluster" { - az $Env:K8sExtensionName delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + az $Env:K8sExtensionName extension delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue # Extension should not be found on the cluster - az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeFalse } It "Performs another list after the delete" { - $output = az $Env:K8sExtensionName list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionName } $extensionExists | Should -BeNullOrEmpty } From c298735fe6c8dc637b588b2e6d62d37f7f818acd Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 22 Jul 2021 12:27:38 -0700 Subject: [PATCH 27/61] Add license header --- .../providers/SourceControlConfigurationProvider.py | 5 +++++ src/k8s-config/setup.cfg | 2 -- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py index 5987d8d85d8..6eb00f237ad 100644 --- a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py @@ -1,3 +1,8 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + from azext_k8s_config.validators import validate_cc_registration, validate_known_hosts, validate_url_with_params from azure.cli.core.azclierror import ResourceNotFoundError from azure.core.exceptions import HttpResponseError diff --git a/src/k8s-config/setup.cfg b/src/k8s-config/setup.cfg index 3c6e79cf31d..e69de29bb2d 100644 --- a/src/k8s-config/setup.cfg +++ b/src/k8s-config/setup.cfg @@ -1,2 +0,0 @@ -[bdist_wheel] -universal=1 From aca146dbf3dfd69f948b0080a19a3cab523af2f9 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 22 Jul 2021 14:59:06 -0700 Subject: [PATCH 28/61] Fix all style issues --- src/k8s-config/azext_k8s_config/__init__.py | 4 +- src/k8s-config/azext_k8s_config/_help.py | 6 +- src/k8s-config/azext_k8s_config/_params.py | 9 +- src/k8s-config/azext_k8s_config/action.py | 19 +- src/k8s-config/azext_k8s_config/consts.py | 2 +- src/k8s-config/azext_k8s_config/custom.py | 44 ++- src/k8s-config/azext_k8s_config/format.py | 2 +- .../partner_extensions/AzureMLKubernetes.py | 2 +- .../partner_extensions/ContainerInsights.py | 2 +- .../partner_extensions/DefaultExtension.py | 2 +- .../DefaultExtensionWithIdentity.py | 2 +- .../partner_extensions/OpenServiceMesh.py | 2 - .../partner_extensions/__init__.py | 7 - .../providers/ExtensionProvider.py | 92 ++--- .../providers/FluxConfigurationProvider.py | 123 +++--- .../SourceControlConfigurationProvider.py | 33 +- .../latest/recordings/test_k8s_extension.yaml | 370 ------------------ .../latest/test_k8s_extension_scenario.py | 12 +- .../test_kubernetesconfiguration_scenario.py | 138 +++++++ .../tests/latest/test_validators.py | 176 +++++++++ src/k8s-config/azext_k8s_config/utils.py | 30 +- src/k8s-config/azext_k8s_config/validators.py | 42 +- 22 files changed, 550 insertions(+), 569 deletions(-) delete mode 100644 src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py create mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_validators.py diff --git a/src/k8s-config/azext_k8s_config/__init__.py b/src/k8s-config/azext_k8s_config/__init__.py index 89b3a9f5821..f2363957f9e 100644 --- a/src/k8s-config/azext_k8s_config/__init__.py +++ b/src/k8s-config/azext_k8s_config/__init__.py @@ -16,8 +16,8 @@ def __init__(self, cli_ctx=None): k8s_config_custom = CliCommandType( operations_tmpl='azext_k8s_config.custom#{}', client_factory=k8s_config_client) - super(k8s_configCommandsLoader, self).__init__(cli_ctx=cli_ctx, - custom_command_type=k8s_config_custom) + super().__init__(cli_ctx=cli_ctx, + custom_command_type=k8s_config_custom) def load_command_table(self, args): from azext_k8s_config.commands import load_command_table diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 32b1959a60e..ea195ea2dcb 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -82,7 +82,7 @@ --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ --kind git --url https://github.com/Azure/arc-k8s-demo --https-user my-username \\ --https-key my-password --branch main --kustomization name=my-crds path="./crds" \\ - --kustomization name=my-apps path="./apps" depends_on=my-crds timeout=PT5M + --kustomization name=my-apps path="./apps" depends_on=my-crds timeout=PT5M """ helps['k8s-config flux list'] = """ @@ -128,7 +128,7 @@ text: |- az k8s-config extension create --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myextension --extension-type microsoft.openservicemesh \\ - --scope cluster --release-train stable + --scope cluster --release-train stable """ helps['k8s-config extension list'] = """ @@ -159,4 +159,4 @@ text: |- az k8s-config extension delete --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myextension -""" \ No newline at end of file +""" diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 7b9d170e80e..876de1ecaa7 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -98,11 +98,11 @@ def load_arguments(self, _): action=KustomizationAddAction, help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", nargs='+') - + with self.argument_context('k8s-config flux delete') as c: c.argument('force', help='Specify whether to force delete the flux configuration from the cluster.') - + with self.argument_context('k8s-config extension create') as c: c.argument('scope', arg_type=get_enum_type(['cluster', 'namespace']), @@ -144,11 +144,11 @@ def load_arguments(self, _): c.argument('target_namespace', help='Specify the target namespace to install to for the extension instance. This' ' parameter is required if extension scope is set to \'namespace\'') - + with self.argument_context('k8s-config extension delete') as c: c.argument('force', help='Specify whether to force delete the extension from the cluster.') - + with self.argument_context('k8s-config flux-v1 create') as c: c.argument('repository_url', options_list=['--repository-url', '-u'], @@ -206,7 +206,6 @@ def load_arguments(self, _): arg_group="Auth", help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') - # with self.argument_context('k8s-config flux source') as c: # c.argument('scope', # options_list=['--scope', '-s'], diff --git a/src/k8s-config/azext_k8s_config/action.py b/src/k8s-config/azext_k8s_config/action.py index 9b772b4f53e..90499a27202 100644 --- a/src/k8s-config/azext_k8s_config/action.py +++ b/src/k8s-config/azext_k8s_config/action.py @@ -27,9 +27,10 @@ def __call__(self, parser, namespace, values, option_string=None): sync_interval = value else: kwargs[key] = value - except ValueError: - raise InvalidArgumentValueError('usage error: {} KEY=VALUE [KEY=VALUE ...]'.format(option_string)) - super(KustomizationAddAction, self).__call__( + except ValueError as ex: + raise InvalidArgumentValueError('usage error: {} KEY=VALUE [KEY=VALUE ...]' + .format(option_string)) from ex + super().__call__( parser, namespace, KustomizationDefinition(depends_on=dependencies, sync_interval=get_duration(sync_interval), **kwargs), @@ -46,10 +47,10 @@ def __call__(self, parser, namespace, values, option_string=None): try: key, value = item.split('=', 1) settings[key] = value - except ValueError: + except ValueError as ex: raise ArgumentUsageError('Usage error: {} configuration_setting_key=configuration_setting_value'. - format(option_string)) - super(AddConfigurationSettings, self).__call__(parser, namespace, settings, option_string) + format(option_string)) from ex + super().__call__(parser, namespace, settings, option_string) # pylint: disable=protected-access, too-few-public-methods @@ -61,7 +62,7 @@ def __call__(self, parser, namespace, values, option_string=None): try: key, value = item.split('=', 1) prot_settings[key] = value - except ValueError: + except ValueError as ex: raise ArgumentUsageError('Usage error: {} configuration_protected_setting_key=' - 'configuration_protected_setting_value'.format(option_string)) - super(AddConfigurationProtectedSettings, self).__call__(parser, namespace, prot_settings, option_string) \ No newline at end of file + 'configuration_protected_setting_value'.format(option_string)) from ex + super().__call__(parser, namespace, prot_settings, option_string) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index ead2ddb3810..a696070a215 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -80,7 +80,7 @@ # PROVIDER REGISTRATION ----------------------------------------- -CC_REGISTRATION_WARNING = "'Flux Configuration' cannot be used because '{0}' provider has not been registered. More details for registering this provider can be found here - {1}" +CC_REGISTRATION_WARNING = "'Flux Configuration' cannot be used because '%s' provider has not been registered. More details for registering this provider can be found here - %s" CC_REGISTRATION_LINK = "https://aka.ms/RegisterKubernetesConfigurationProvider" CC_REGISTRATION_ERROR = "Unable to fetch registration state of '{0}' provider. Failed to enable 'flux configuration' feature..." CC_PROVIDER_NAMESPACE = 'Microsoft.KubernetesConfiguration' diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index de238821492..3eb43fd6057 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -3,14 +3,16 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +# pylint: disable=unused-argument + from azext_k8s_config.providers.SourceControlConfigurationProvider import SourceControlConfigurationProvider from .providers.ExtensionProvider import ExtensionProvider from .providers.FluxConfigurationProvider import FluxConfigurationProvider -from .utils import get_cluster_rp from . import consts # Source Control Configuration Methods + def sourcecontrol_create(cmd, client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, operator_instance_name=None, operator_namespace='default', helm_operator_chart_version='1.2.0', operator_type='flux', operator_params='', @@ -23,6 +25,7 @@ def sourcecontrol_create(cmd, client, resource_group_name, cluster_name, name, r operator_params, ssh_private_key, ssh_private_key_file, https_user, https_key, ssh_known_hosts, ssh_known_hosts_file, enable_helm_operator, helm_operator_params) + def sourcecontrol_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): provider = SourceControlConfigurationProvider(cmd) return provider.show(resource_group_name, cluster_type, cluster_name, name) @@ -58,30 +61,33 @@ def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_n known_hosts_file=None, kustomization=None): provider = FluxConfigurationProvider(cmd) - return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, - branch, tag, semver, commit, local_auth_ref, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, - known_hosts_file, kustomization) + return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, + timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, kustomization) def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, - branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, - ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None): - + branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, + ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, + known_hosts=None, known_hosts_file=None): + provider = FluxConfigurationProvider(cmd) - return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, - branch, tag, semver, commit, local_auth_ref, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, + return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, + kind, timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, + ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file) -def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, kustomization_name, - dependencies=None, timeout=None, sync_interval=None, retry_interval=None, path='', prune=False, validation='none', force=False): - + +def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, + kustomization_name, dependencies=None, timeout=None, sync_interval=None, + retry_interval=None, path='', prune=False, validation='none', force=False): + provider = FluxConfigurationProvider(cmd) return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, - dependencies, timeout, sync_interval, retry_interval, path, prune, validation, force) + dependencies, timeout, sync_interval, retry_interval, path, prune, + validation, force) + def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False): provider = FluxConfigurationProvider(cmd) @@ -106,8 +112,10 @@ def extension_create(cmd, client, resource_group_name, cluster_type, cluster_nam configuration_protected_settings=None, configuration_settings_file=None, configuration_protected_settings_file=None, tags=None): provider = ExtensionProvider(cmd) - return provider.create(resource_group_name, cluster_type, cluster_name, name, extension_type, scope, auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, - configuration_settings, configuration_protected_settings, configuration_settings_file, configuration_protected_settings_file) + return provider.create(resource_group_name, cluster_type, cluster_name, name, extension_type, scope, + auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file) def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False): diff --git a/src/k8s-config/azext_k8s_config/format.py b/src/k8s-config/azext_k8s_config/format.py index b06fcb6f9b9..42075acbb14 100644 --- a/src/k8s-config/azext_k8s_config/format.py +++ b/src/k8s-config/azext_k8s_config/format.py @@ -55,4 +55,4 @@ def __get_fluxconfig_table_row(result): print(result) return OrderedDict([ ('name', result['name']), - ]) \ No newline at end of file + ]) diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py index f188f76afc1..a0cb1726df4 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py @@ -28,7 +28,7 @@ from .._client_factory import cf_resources from .PartnerExtensionModel import PartnerExtensionModel -from ..vendored_sdks.v2021_05_01_preview.models import( +from ..vendored_sdks.v2021_05_01_preview.models import ( Extension, ScopeCluster, Scope diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py index 9b19a338f6c..e6e6b3c2023 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py @@ -16,7 +16,7 @@ from azure.cli.core.util import sdk_no_wait from msrestazure.tools import parse_resource_id, is_valid_resource_id -from ..vendored_sdks.v2021_05_01_preview.models import( +from ..vendored_sdks.v2021_05_01_preview.models import ( Extension, ScopeCluster, Scope diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py index 8518fb97a60..a04893f55e7 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py @@ -5,7 +5,7 @@ # pylint: disable=unused-argument -from ..vendored_sdks.v2021_05_01_preview.models import( +from ..vendored_sdks.v2021_05_01_preview.models import ( Extension, ScopeCluster, ScopeNamespace, diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py index 2e53a730c5f..aeb83028c52 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py @@ -5,7 +5,7 @@ # pylint: disable=unused-argument -from ..vendored_sdks.v2021_05_01_preview.models import( +from ..vendored_sdks.v2021_05_01_preview.models import ( Extension, ScopeCluster, ScopeNamespace, diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py b/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py index 010a0b3c1fc..d2c95b74588 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py @@ -15,8 +15,6 @@ from packaging import version import yaml -from ..partner_extensions import PartnerExtensionModel - from .PartnerExtensionModel import PartnerExtensionModel from ..vendored_sdks.v2021_05_01_preview .models import ( diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py b/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py index 7405deadd6b..e69de29bb2d 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py @@ -1,7 +0,0 @@ -# ----------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ----------------------------------------------------------------------------- - -from ..vendored_sdks.v2021_05_01_preview import models as models \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index 3d7d9e733e7..f3a3a36979d 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -9,8 +9,7 @@ from azure.core.exceptions import HttpResponseError -from azure.cli.core.azclierror import ResourceNotFoundError, MutuallyExclusiveArgumentError, \ - InvalidArgumentValueError, CommandNotFoundError, RequiredArgumentMissingError +from azure.cli.core.azclierror import ResourceNotFoundError, MutuallyExclusiveArgumentError from azure.cli.core.commands.client_factory import get_subscription_id from ..vendored_sdks.v2021_05_01_preview.models import Identity @@ -21,7 +20,12 @@ from ..partner_extensions.DefaultExtension import DefaultExtension from ..partner_extensions.DefaultExtensionWithIdentity import DefaultExtensionWithIdentity -from ..utils import get_cluster_rp, read_config_settings_file +from ..utils import get_cluster_rp, get_parent_api_version, read_config_settings_file +from ..validators import ( + validate_scope_and_namespace, + validate_version_and_auto_upgrade, + validate_scope_after_customization +) from .._client_factory import cf_resources from .._client_factory import k8s_config_extension_client @@ -48,13 +52,12 @@ def __init__(self, cmd): self.cmd = cmd self.client = k8s_config_extension_client(cmd.cli_ctx) - def show(self, resource_group_name, cluster_type, cluster_name, name): # Determine ClusterRP cluster_rp = get_cluster_rp(cluster_type) try: - extension = self.client.get(resource_group_name, - cluster_rp, cluster_type, cluster_name, name) + extension = self.client.get(resource_group_name, cluster_rp, + cluster_type, cluster_name, name) return extension except HttpResponseError as ex: # Customize the error message for resources not found @@ -66,25 +69,28 @@ def show(self, resource_group_name, cluster_type, cluster_name, name): # If Configuration not found elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): message = "(ExtensionNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/" \ - "extensions/{3} could not be found!".format( - cluster_rp, cluster_type, cluster_name, name) + "extensions/{3} could not be found!".format(cluster_rp, cluster_type, + cluster_name, name) else: message = ex.message - raise ResourceNotFoundError(message) - + raise ResourceNotFoundError(message) from ex + raise ex def list(self, resource_group_name, cluster_type, cluster_name): cluster_rp = get_cluster_rp(cluster_type) return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - def delete(self, resource_group_name, cluster_type, cluster_name, name, force): cluster_rp = get_cluster_rp(cluster_type) if not force: logger.info("Delting the flux configuration from the cluster. This may take a minute...") - return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name, force_delete=force) - + return self.client.begin_delete(resource_group_name, + cluster_rp, + cluster_type, + cluster_name, + name, + force_delete=force) def create(self, resource_group_name, cluster_type, cluster_name, name, extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, @@ -134,7 +140,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, extension_instance = None # Scope & Namespace validation - common to all extension-types - self.__validate_scope_and_namespace(scope, release_namespace, target_namespace) + validate_scope_and_namespace(scope, release_namespace, target_namespace) # Give Partners a chance to their extensionType specific validations and to set value over-rides. @@ -146,41 +152,25 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, config_protected_settings, configuration_settings_file, configuration_protected_settings_file) # Common validations - self.__validate_version_and_auto_upgrade(extension_instance.version, extension_instance.auto_upgrade_minor_version) - self.__validate_scope_after_customization(extension_instance.scope) + validate_version_and_auto_upgrade(extension_instance.version, + extension_instance.auto_upgrade_minor_version) + validate_scope_after_customization(extension_instance.scope) # Create identity, if required if create_identity: - extension_instance = self.__add_identity(extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name) + extension_instance = self.__add_identity(extension_instance, + resource_group_name, + cluster_rp, + cluster_type, + cluster_name) logger.info("Starting extension creation on the cluster. This might take a minute...") - return self.client.begin_create(resource_group_name, cluster_rp, cluster_type, cluster_name, name, extension_instance) - - def __validate_scope_and_namespace(self, scope, release_namespace, target_namespace): - if scope == 'cluster': - if target_namespace is not None: - message = "When --scope is 'cluster', --target-namespace must not be given." - raise MutuallyExclusiveArgumentError(message) - else: - if release_namespace is not None: - message = "When --scope is 'namespace', --release-namespace must not be given." - raise MutuallyExclusiveArgumentError(message) - - - def __validate_scope_after_customization(self, scope_obj): - if scope_obj is not None and scope_obj.namespace is not None and scope_obj.namespace.target_namespace is None: - message = "When --scope is 'namespace', --target-namespace must be given." - raise RequiredArgumentMissingError(message) - - - def __validate_version_and_auto_upgrade(self, version, auto_upgrade_minor_version): - if version is not None: - if auto_upgrade_minor_version: - message = "To pin to specific version, auto-upgrade-minor-version must be set to 'false'." - raise MutuallyExclusiveArgumentError(message) - - auto_upgrade_minor_version = False - + return self.client.begin_create(resource_group_name, + cluster_rp, + cluster_type, + cluster_name, + name, + extension_instance) def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name): subscription_id = get_subscription_id(self.cmd.cli_ctx) @@ -192,24 +182,14 @@ def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cl cluster_type, cluster_name) - parent_api_version = self.__get_parent_api_version(cluster_rp) + parent_api_version = get_parent_api_version(cluster_rp) try: resource = resources.get_by_id(cluster_resource_id, parent_api_version) location = str(resource.location.lower()) except HttpResponseError as ex: raise ex identity_type = "SystemAssigned" - + extension_instance.identity = Identity(type=identity_type) extension_instance.location = location return extension_instance - - def __get_parent_api_version(self, cluster_rp): - if cluster_rp == 'Microsoft.Kubernetes': - return '2020-01-01-preview' - elif cluster_rp == 'Microsoft.ResourceConnector': - return '2020-09-15-privatepreview' - elif cluster_rp == 'Microsoft.ContainerService': - return '2017-07-01' - else: - raise InvalidArgumentValueError("Error! Cluster RP '{}' is not supported for extension identity".format(cluster_rp)) \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 1ec54af9c62..f0bb6500bb9 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -3,6 +3,8 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +# pylint: disable=unused-argument + from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property from azure.core.exceptions import HttpResponseError @@ -25,19 +27,20 @@ FluxConfiguration, GitRepositoryDefinition, RepositoryRefDefinition, + KustomizationDefinition, ) from .ExtensionProvider import ExtensionProvider from .SourceControlConfigurationProvider import SourceControlConfigurationProvider logger = get_logger(__name__) + class FluxConfigurationProvider: def __init__(self, cmd): self.extension_provider = ExtensionProvider(cmd) self.source_control_configuration_provider = SourceControlConfigurationProvider(cmd) self.cmd = cmd self.client = k8s_config_fluxconfig_client(cmd.cli_ctx) - def show(self, resource_group_name, cluster_type, cluster_name, name): """Get an existing Kubernetes Source Control Configuration. @@ -55,29 +58,31 @@ def show(self, resource_group_name, cluster_type, cluster_name, name): if ex.message.__contains__("(ResourceNotFound)"): message = ex.message recommendation = 'Verify that the --cluster-type is correct and the Resource ' \ - '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name) + '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name) # If Configuration not found elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): - message = '(FluxConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \ - 'fluxConfigurations/{3} could not be found!'.format(cluster_rp, cluster_type, - cluster_name, name) + message = '(FluxConfigurationNotFound) The Resource {0}/{1}/{2}/' \ + 'Microsoft.KubernetesConfiguration/fluxConfigurations/{3} ' \ + 'could not be found!' \ + .format(cluster_rp, cluster_type, cluster_name, name) recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \ - '/fluxConfigurations/{3} exists'.format(cluster_rp, cluster_type, - cluster_name, name) + '/fluxConfigurations/{3} exists'.format(cluster_rp, cluster_type, + cluster_name, name) else: message = ex.message recommendation = '' raise ResourceNotFoundError(message, recommendation) from ex + raise ex def list(self, resource_group_name, cluster_type, cluster_name): cluster_rp = get_cluster_rp(cluster_type) return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - # pylint: disable=too-many-locals - def create(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', - kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, - ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + def create(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', + namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, + tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, + ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None, kustomization=None): # Determine the cluster RP @@ -90,9 +95,11 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None if kind == consts.GIT: dp_source_kind = consts.GIT_REPOSITORY - git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, - known_hosts_file, local_auth_ref) + git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, + sync_interval, ssh_private_key, + ssh_private_key_file, https_user, + https_key, known_hosts, known_hosts_file, + local_auth_ref) if kustomization: validate_kustomization_list(kustomization) @@ -109,10 +116,11 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None return self.client.begin_create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) - - def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', - kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, - ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + + def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', + namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, + tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, + ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, known_hosts_file=None): # Determine the cluster RP cluster_rp = get_cluster_rp(cluster_type) @@ -126,10 +134,12 @@ def create_source(self, resource_group_name, cluster_type, cluster_name, name, u if kind == consts.GIT: dp_source_kind = consts.GIT_REPOSITORY - git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, + git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, + timeout, sync_interval, + ssh_private_key, ssh_private_key_file, + https_user, https_key, known_hosts, known_hosts_file, local_auth_ref) - + flux_configuration = FluxConfiguration( scope=scope, namespace=namespace, @@ -139,21 +149,26 @@ def create_source(self, resource_group_name, cluster_type, cluster_name, name, u ) # cache the payload if --defer used or send to Azure - return cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, - flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, + return cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, + resource_group_name=resource_group_name, flux_configuration_name=name, + cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name, setter_arg_name='flux_configuration') - def create_kustomization(self, resource_group_name, cluster_type, cluster_name, name, kustomization_name, - dependencies, timeout, sync_interval, retry_interval, path='', prune=False, validation='none', force=False): + def create_kustomization(self, resource_group_name, cluster_type, cluster_name, name, + kustomization_name, dependencies, timeout, sync_interval, + retry_interval, path='', prune=False, validation='none', + force=False): # Determine ClusterRP cluster_rp = get_cluster_rp(cluster_type) - + # Validate the extension install if this is not a deferred command if not self._is_deferred(): self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) self._validate_extension_install(resource_group_name, cluster_type, cluster_name) - flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name) + flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name=resource_group_name, + flux_configuration_name=name, cluster_rp=cluster_rp, + cluster_resource_name=cluster_type, cluster_name=cluster_name) kustomization = KustomizationDefinition( name=name, @@ -171,33 +186,36 @@ def create_kustomization(self, resource_group_name, cluster_type, cluster_name, validate_kustomization_list(proposed_change) upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') - flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, cluster_name=cluster_name, setter_arg_name='flux_configuration') + flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, + resource_group_name=resource_group_name, flux_configuration_name=name, + cluster_rp=cluster_rp, cluster_resource_name=cluster_type, + cluster_name=cluster_name, setter_arg_name='flux_configuration') return get_property(flux_configuration.kustomizations, name) - def delete(self, client, resource_group_name, cluster_type, cluster_name, name, force): + def delete(self, resource_group_name, cluster_type, cluster_name, name, force): cluster_rp = get_cluster_rp(cluster_type) if not force: logger.info("Delting the flux configuration from the cluster. This may take a minute...") - return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name, force_delete=force) + return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, + cluster_name, name, force_delete=force) def _is_deferred(self): - return if '--defer' in self.cmd.cli_ctx.data.get('safe_params'): return True return False def _validate_source_control_config_not_installed(self, resource_group_name, cluster_type, cluster_name): - # Validate if we are able to install the flux configuration + # Validate if we are able to install the flux configuration configs = self.source_control_configuration_provider.list(resource_group_name, cluster_type, cluster_name) # configs is an iterable, no len() so we have to iterate to check for configs for _ in configs: raise DeploymentError( consts.SCC_EXISTS_ON_CLUSTER_ERROR, consts.SCC_EXISTS_ON_CLUSTER_HELP) - + def _validate_extension_install(self, resource_group_name, cluster_type, cluster_name): - # Validate if the extension is installed, if not, install it + # Validate if the extension is installed, if not, install it extensions = self.extension_provider.list(resource_group_name, cluster_type, cluster_name) found_flux_extension = False for extension in extensions: @@ -205,12 +223,15 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster found_flux_extension = True break if not found_flux_extension: - logger.info("'Micrsoft.Flux' extension not found on the cluster, installing it now. This may take a minute...") - self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE).result() + logger.info("'Micrsoft.Flux' extension not found on the cluster, installing it now." + " This may take a minute...") + self.extension_provider.create(resource_group_name, cluster_type, cluster_name, + "flux", consts.FLUX_EXTENSION_TYPE).result() logger.info("'Microsoft.Flux' extension was successfully installed on the cluster") - def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, local_auth_ref): + def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, + ssh_private_key, ssh_private_key_file, https_user, https_key, + known_hosts, known_hosts_file, local_auth_ref): # Pre-Validation validate_duration("--timeout", timeout) validate_duration("--sync-interval", sync_interval) @@ -232,10 +253,9 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time validate_git_repository(url) validate_url_with_params(url, ssh_private_key, ssh_private_key_file, - known_hosts, known_hosts_file, https_user, https_key) + known_hosts, known_hosts_file, https_user, https_key) - repository_ref = self._validate_and_get_repository_ref(branch, tag, semver, commit) - + repository_ref = validate_and_get_repository_ref(branch, tag, semver, commit) return GitRepositoryDefinition( url=url, @@ -246,13 +266,14 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time https_user=https_user, local_auth_ref=local_auth_ref ) - - def _validate_and_get_repository_ref(self, branch, tag, semver, commit): - validate_repository_ref(branch, tag, semver, commit) - - return RepositoryRefDefinition( - branch=branch, - tag=tag, - semver=semver, - commit=commit - ) + + +def validate_and_get_repository_ref(branch, tag, semver, commit): + validate_repository_ref(branch, tag, semver, commit) + + return RepositoryRefDefinition( + branch=branch, + tag=tag, + semver=semver, + commit=commit + ) diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py index 6eb00f237ad..a289d33202d 100644 --- a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py @@ -24,13 +24,13 @@ def __init__(self, cmd): self.cmd = cmd self.client = k8s_config_sourcecontrol_client(cmd.cli_ctx) - def show(self, resource_group_name, cluster_type, cluster_name, name): # Determine ClusterRP cluster_rp = get_cluster_rp(cluster_type) try: extension = self.client.get(resource_group_name, - cluster_rp, cluster_type, cluster_name, name) + cluster_rp, cluster_type, + cluster_name, name) return extension except HttpResponseError as ex: # Customize the error message for resources not found @@ -41,19 +41,19 @@ def show(self, resource_group_name, cluster_type, cluster_name, name): ex.message) # If Configuration not found elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): - message = "(SourceControlConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/" \ - "sourceControlConfigurations/{3} could not be found!".format( - self.cluster_rp, self.cluster_type, self.cluster_name, self.name) + message = "(SourceControlConfigurationNotFound) The Resource {0}/{1}/{2}/" \ + "Microsoft.KubernetesConfiguration/sourceControlConfigurations/{3}" \ + "could not be found!".format(cluster_rp, cluster_type, + cluster_name, name) else: message = ex.message - raise ResourceNotFoundError(message) - + raise ResourceNotFoundError(message) from ex + raise ex def list(self, resource_group_name, cluster_type, cluster_name): cluster_rp = get_cluster_rp(cluster_type) return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - def delete(self, resource_group_name, cluster_type, cluster_name, name): cluster_rp = get_cluster_rp(cluster_type) return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, name) @@ -63,7 +63,7 @@ def create(self, resource_group_name, cluster_name, name, repository_url, scope, operator_instance_name, operator_namespace, helm_operator_chart_version, operator_type, operator_params, ssh_private_key, ssh_private_key_file, https_user, https_key, ssh_known_hosts, ssh_known_hosts_file, enable_helm_operator, helm_operator_params): - + """Create a new Kubernetes Source Control Configuration. """ @@ -89,14 +89,13 @@ def create(self, resource_group_name, cluster_name, name, repository_url, scope, if knownhost_data: validate_known_hosts(knownhost_data) - # Flag which parameters have been set and validate these settings against the set repository url - ssh_private_key_set = ssh_private_key != '' or ssh_private_key_file != '' - known_hosts_contents_set = knownhost_data != '' - https_auth_set = https_user != '' and https_key != '' validate_url_with_params(repository_url, - ssh_private_key_set=ssh_private_key_set, - known_hosts_contents_set=known_hosts_contents_set, - https_auth_set=https_auth_set) + ssh_private_key, + ssh_private_key_file, + ssh_known_hosts, + ssh_known_hosts_file, + https_user, + https_key) # Validate that the subscription is registered to Microsoft.KubernetesConfiguration validate_cc_registration(self.cmd) @@ -119,4 +118,4 @@ def create(self, resource_group_name, cluster_name, name, repository_url, scope, config = self.client.create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, name, source_control_configuration) - return fix_compliance_state(config) \ No newline at end of file + return fix_compliance_state(config) diff --git a/src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml b/src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml deleted file mode 100644 index 7419d9c22bf..00000000000 --- a/src/k8s-config/azext_k8s_config/tests/latest/recordings/test_k8s_extension.yaml +++ /dev/null @@ -1,370 +0,0 @@ -interactions: -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-extension create - Connection: - - keep-alive - ParameterSetName: - - -g -n -c --cluster-type --extension-type --release-train --version - User-Agent: - - AZURECLI/2.24.2 azsdk-python-azure-mgmt-resource/18.0.0 Python/3.9.0 (Windows-10-10.0.19041-SP0) - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.KubernetesConfiguration?api-version=2021-04-01 - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.KubernetesConfiguration","namespace":"Microsoft.KubernetesConfiguration","authorizations":[{"applicationId":"c699bf69-fb1d-4eaf-999b-99e6b2ae4d85","roleDefinitionId":"90155430-a360-410f-af5d-89dc284d85c6"},{"applicationId":"03db181c-e9d3-4868-9097-f0b728327182","roleDefinitionId":"DE2ADB97-42D8-49C8-8FCF-DBB53EF936AC"},{"applicationId":"a0f92522-89de-4c5e-9a75-0044ccf66efd","roleDefinitionId":"b3429810-7d5c-420e-8605-cf280f3099f2"},{"applicationId":"bd9b7cd5-dac1-495f-b013-ac871e98fa5f","roleDefinitionId":"0d44c8f0-08b9-44d4-9f59-e51c83f95200"}],"resourceTypes":[{"resourceType":"sourceControlConfigurations","locations":["East - US","West Europe","West Central US","West US 2","South Central US","East US - 2","North Europe","UK South","Southeast Asia","Australia East","France Central","East - US 2 EUAP"],"apiVersions":["2021-03-01","2020-10-01-preview","2020-07-01-preview","2019-11-01-preview"],"defaultApiVersion":"2021-03-01","capabilities":"SupportsExtension"},{"resourceType":"extensions","locations":["East - US","West Europe","West Central US","West US 2","South Central US","East US - 2","North Europe","UK South","Southeast Asia","Australia East","France Central","East - US 2 EUAP"],"apiVersions":["2021-05-01-preview","2020-07-01-preview"],"capabilities":"SystemAssignedResourceIdentity, - SupportsExtension"},{"resourceType":"operations","locations":[],"apiVersions":["2021-05-01-preview","2021-03-01","2020-10-01-preview","2020-07-01-preview","2019-11-01-preview"],"capabilities":"None"}],"registrationState":"Registered","registrationPolicy":"RegistrationRequired"}' - headers: - cache-control: - - no-cache - content-length: - - '1654' - content-type: - - application/json; charset=utf-8 - date: - - Tue, 22 Jun 2021 23:19:11 GMT - expires: - - '-1' - pragma: - - no-cache - strict-transport-security: - - max-age=31536000; includeSubDomains - vary: - - Accept-Encoding - x-content-type-options: - - nosniff - status: - code: 200 - message: OK -- request: - body: '{"location": "", "properties": {"extensionType": "microsoft.openservicemesh", - "autoUpgradeMinorVersion": false, "releaseTrain": "pilot", "version": "0.8.3", - "scope": {"cluster": {}}, "configurationSettings": {}, "configurationProtectedSettings": - {}}}' - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-extension create - Connection: - - keep-alive - Content-Length: - - '250' - Content-Type: - - application/json; charset=utf-8 - ParameterSetName: - - -g -n -c --cluster-type --extension-type --release-train --version - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 - accept-language: - - en-US - method: PUT - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"configurationSettings":{},"statuses":[],"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}}' - headers: - api-supported-versions: - - 2020-07-01-Preview, 2021-05-01-preview - cache-control: - - no-cache - content-length: - - '704' - content-type: - - application/json; charset=utf-8 - date: - - Tue, 22 Jun 2021 23:19:13 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding,Accept-Encoding - x-content-type-options: - - nosniff - x-ms-ratelimit-remaining-subscription-writes: - - '1199' - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-extension list - Connection: - - keep-alive - ParameterSetName: - - -c -g --cluster-type - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions?api-version=2020-07-01-preview - response: - body: - string: '{"value":[{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}},{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/hci22jan21","name":"hci22jan21","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"extensionType":"microsoft.azstackhci.operator","autoUpgradeMinorVersion":true,"releaseTrain":"stable","version":"1.0.0","scope":{"cluster":{"releaseNamespace":null}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-01-22T20:49:34.3336157+00:00","lastModifiedTime":"2021-01-22T20:49:34.3336249+00:00"}}],"nextLink":null}' - headers: - api-supported-versions: - - 2020-07-01-Preview, 2021-05-01-preview - cache-control: - - no-cache - content-length: - - '1337' - content-type: - - application/json; charset=utf-8 - date: - - Tue, 22 Jun 2021 23:19:14 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding,Accept-Encoding - x-content-type-options: - - nosniff - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-extension show - Connection: - - keep-alive - ParameterSetName: - - -c -g -n --cluster-type - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"configurationSettings":{},"statuses":[],"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}}' - headers: - api-supported-versions: - - 2020-07-01-Preview, 2021-05-01-preview - cache-control: - - no-cache - content-length: - - '704' - content-type: - - application/json; charset=utf-8 - date: - - Tue, 22 Jun 2021 23:19:15 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding,Accept-Encoding - x-content-type-options: - - nosniff - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-extension delete - Connection: - - keep-alive - ParameterSetName: - - -g -c -n --cluster-type -y - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh","name":"openservicemesh","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"configurationSettings":{},"statuses":[],"extensionType":"microsoft.openservicemesh","autoUpgradeMinorVersion":false,"releaseTrain":"pilot","version":"0.8.3","scope":{"cluster":{"releaseNamespace":"arc-osm-system"}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-06-22T23:19:13.9750935+00:00","lastModifiedTime":"2021-06-22T23:19:13.9750935+00:00"}}' - headers: - api-supported-versions: - - 2020-07-01-Preview, 2021-05-01-preview - cache-control: - - no-cache - content-length: - - '704' - content-type: - - application/json; charset=utf-8 - date: - - Tue, 22 Jun 2021 23:19:16 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding,Accept-Encoding - x-content-type-options: - - nosniff - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-extension delete - Connection: - - keep-alive - Content-Length: - - '0' - ParameterSetName: - - -g -c -n --cluster-type -y - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 - accept-language: - - en-US - method: DELETE - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/openservicemesh?api-version=2020-07-01-preview - response: - body: - string: '{"content":null,"statusCode":200,"headers":[],"version":"1.1","reasonPhrase":"OK","trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true}' - headers: - api-supported-versions: - - 2020-07-01-Preview, 2021-05-01-preview - cache-control: - - no-cache - content-length: - - '152' - content-type: - - application/json; charset=utf-8 - date: - - Tue, 22 Jun 2021 23:19:17 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding - x-content-type-options: - - nosniff - x-ms-ratelimit-remaining-subscription-deletes: - - '14999' - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-extension list - Connection: - - keep-alive - ParameterSetName: - - -c -g --cluster-type - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.3.0 Azure-SDK-For-Python AZURECLI/2.24.2 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions?api-version=2020-07-01-preview - response: - body: - string: '{"value":[{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/extensions/hci22jan21","name":"hci22jan21","type":"Microsoft.KubernetesConfiguration/extensions","properties":{"extensionType":"microsoft.azstackhci.operator","autoUpgradeMinorVersion":true,"releaseTrain":"stable","version":"1.0.0","scope":{"cluster":{"releaseNamespace":null}},"installState":"Pending","lastStatusTime":null,"errorInfo":{},"creationTime":"2021-01-22T20:49:34.3336157+00:00","lastModifiedTime":"2021-01-22T20:49:34.3336249+00:00"}}],"nextLink":null}' - headers: - api-supported-versions: - - 2020-07-01-Preview, 2021-05-01-preview - cache-control: - - no-cache - content-length: - - '673' - content-type: - - application/json; charset=utf-8 - date: - - Tue, 22 Jun 2021 23:19:19 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding,Accept-Encoding - x-content-type-options: - - nosniff - status: - code: 200 - message: OK -version: 1 diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py index 53db4ce2c2d..392efe41300 100644 --- a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py @@ -26,7 +26,7 @@ def test_k8s_extension(self): 'version': '0.8.3' }) - self.cmd('k8s-extension create -g {rg} -n {name} -c {cluster_name} --cluster-type {cluster_type} ' + self.cmd('k8s-config extension create -g {rg} -n {name} -c {cluster_name} --cluster-type {cluster_type} ' '--extension-type {extension_type} --release-train {release_train} --version {version}', checks=[ self.check('name', '{name}'), @@ -38,11 +38,11 @@ def test_k8s_extension(self): ) # Update is disabled for now - # self.cmd('k8s-extension update -g {rg} -n {name} --tags foo=boo', checks=[ + # self.cmd('k8s-config extension update -g {rg} -n {name} --tags foo=boo', checks=[ # self.check('tags.foo', 'boo') # ]) - installed_exts = self.cmd('k8s-extension list -c {cluster_name} -g {rg} --cluster-type {cluster_type}').get_output_in_json() + installed_exts = self.cmd('k8s-config extension list -c {cluster_name} -g {rg} --cluster-type {cluster_type}').get_output_in_json() found_extension = False for item in installed_exts: if item['extensionType'] == resource_type: @@ -50,7 +50,7 @@ def test_k8s_extension(self): break self.assertTrue(found_extension) - self.cmd('k8s-extension show -c {cluster_name} -g {rg} -n {name} --cluster-type {cluster_type}', checks=[ + self.cmd('k8s-config extension show -c {cluster_name} -g {rg} -n {name} --cluster-type {cluster_type}', checks=[ self.check('name', '{name}'), self.check('releaseTrain', '{release_train}'), self.check('version', '{version}'), @@ -58,9 +58,9 @@ def test_k8s_extension(self): self.check('extensionType', '{extension_type}') ]) - self.cmd('k8s-extension delete -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type} -y') + self.cmd('k8s-config extension delete -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type} -y') - installed_exts = self.cmd('k8s-extension list -c {cluster_name} -g {rg} --cluster-type {cluster_type}').get_output_in_json() + installed_exts = self.cmd('k8s-config extension list -c {cluster_name} -g {rg} --cluster-type {cluster_type}').get_output_in_json() found_extension = False for item in installed_exts: if item['extensionType'] == resource_type: diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py b/src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py new file mode 100644 index 00000000000..dfe285b1e2b --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py @@ -0,0 +1,138 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import os + +from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, record_only) +from azure.cli.core.azclierror import InvalidArgumentValueError, ResourceNotFoundError + +TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + + +class K8sConfigurationScenarioTest(ScenarioTest): + @ResourceGroupPreparer(name_prefix='cli_test_k8s_configuration') + @record_only() + def test_k8s_configuration_success(self): + + # -------------------------------------------------------------------- + # SSH SCENARIO TEST + # -------------------------------------------------------------------- + self.kwargs.update({ + 'name': 'cli-test-config10', + 'cluster_name': 'nanthicluster0923', + 'rg': 'nanthirg0923', + 'repo_url': 'git://github.com/anubhav929/flux-get-started', + 'operator_instance_name': 'cli-test-config10-opin', + 'operator_namespace': 'cli-test-config10-opns', + 'cluster_type': 'connectedClusters', + 'scope': 'namespace', + 'ssh_private_key': 'LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFZRUFxZlBtNlc3YkVLTmVvN3VCQzhTMXYydUpPS1NZWGNmanlpVEk2djNkZUhRSjJtMGFRajB0CmtwM05qMUZkRUsrMkVXTy9xNGFkWUpaS0ZZSjluWTZyREZOSXBZdmVWaVNUQjhITzI5VVdySTRLVGZMRGhiVmVCV0pjQVcKMkFpZ0ZnTU5qdTZXa0JVL1NWK1FCVHJiRVl6RFhpOTVNR1ZveTVKV3drdkdtakRaOHFSaEFxbU0rdUF4S1I4Z1lyRllPZgpRbC9zM2I5ajJKQ1VtVFlwYkxqMkJPd0JNQ1J3NlFQY0lVcVlaaUl3MUNNaXZKZ2tVQTdwUlRCZHVsYXlXNWQ2MTl4RFNsCmZ6N1JuU0tKM3RwanEwZThBTmtkU1h4SjQrMXhpNm5IM0lVY1ZBM1NzcVhWam80ak5sNU5EWkJlTDNpQ0xXSVZYUkpDemsKNGg3a2pXVkQ3UnNDNGJDOTF6MzlZMDlnK3ZIdjErZFplUmNYZWIvNkFzbTBEeHVhRGo2cVVCVm9JOWkwbzFKbndiMnA0MQpGV2prazljc054a2dnajMzU3ozTWJRTVN0bTFLaWU2bHNRamlMUXdGT3Qwd3lFTnova2RUR25idkVMUTN3aWdUdVFrelFOCnlMR2dmK3FXZnhqL1l1MWt5b0xrQVpqT3JxdEttalVILzk3Y3lncWhBQUFGa08zNi9uWHQrdjUxQUFBQUIzTnphQzF5YzIKRUFBQUdCQUtuejV1bHUyeENqWHFPN2dRdkV0YjlyaVRpa21GM0g0OG9reU9yOTNYaDBDZHB0R2tJOUxaS2R6WTlSWFJDdgp0aEZqdjZ1R25XQ1dTaFdDZloyT3F3eFRTS1dMM2xZa2t3ZkJ6dHZWRnF5T0NrM3l3NFcxWGdWaVhBRnRnSW9CWUREWTd1CmxwQVZQMGxma0FVNjJ4R013MTR2ZVRCbGFNdVNWc0pMeHBvdzJmS2tZUUtwalByZ01Ta2ZJR0t4V0RuMEpmN04yL1k5aVEKbEprMktXeTQ5Z1RzQVRBa2NPa0QzQ0ZLbUdZaU1OUWpJcnlZSkZBTzZVVXdYYnBXc2x1WGV0ZmNRMHBYOCswWjBpaWQ3YQpZNnRIdkFEWkhVbDhTZVB0Y1l1cHg5eUZIRlFOMHJLbDFZNk9JelplVFEyUVhpOTRnaTFpRlYwU1FzNU9JZTVJMWxRKzBiCkF1R3d2ZGM5L1dOUFlQcng3OWZuV1hrWEYzbS8rZ0xKdEE4Ym1nNCtxbEFWYUNQWXRLTlNaOEc5cWVOUlZvNUpQWExEY1oKSUlJOTkwczl6RzBERXJadFNvbnVwYkVJNGkwTUJUcmRNTWhEYy81SFV4cDI3eEMwTjhJb0U3a0pNMERjaXhvSC9xbG44WQovMkx0Wk1xQzVBR1l6cTZyU3BvMUIvL2UzTW9Lb1FBQUFBTUJBQUVBQUFHQkFKSnJUVTlqY0Z4ZlE1UHdZUGRRbS95MG10CjR3QUEwYnY0WlNOcjh0dy9hWWtqeWFybnJPMWtwd3BiNkpySkpKcjZRL3Vjdi9CK3RFejhMRVQ1REViMTBKQzVlRWJ5THMKRTdnbEl5Q0Y3eWp1bnJZVkpwbzFiVEZhVWtYd24wTkdlQ2JkWHNlODdhWDFISmdQemdmZ2dhcTk2aks5ZWtKcXJzQXM4VwpGWjZWNDgrR0N3WU9LU1dpclBmdWx5b3YvQURCOVZJVzdTQ3lWek9uTGRGTWRVZXJBMjI3Y3NUaEtTZnI0MzFDQjU2SE43CmFkdnRmNnR4alV0TXBoTjV5ZVBiRmxVZS9Wb2VQY1hNdXA4OXN3V2gvd3ZScklCbytUYXo2SzQxcGFzOEVObjFyemFxL3kKRHlWelJuSGtlMGhKR2ZZelJhbzlZQm5jeHFMOCtXdDQxZFFzQUdhdlIwd3ZNSit5TFpuR0x5amVXaVZkcExjT0FWSGpIOQpITGMrTDdnaGpIZ1VidDNDWG9Wd0gyWktnelI5cmk3bU93YnorejZsN1pwWjlQalJxeU1HcTloYU5vNHVEdjJqbWhGNlZVClBMU2Q3WTczWCtWTFAvWUZqbTBlUzJUbGFRQ3E2Vms0dzJqSHVWcXorcng4SllYb2tidFZXYnFYcmg3VzF5VGk4MXVRQUEKQU1Ba0JaQzF0SThvd29SNDYvL1h1SWQxQjBGRUhGUXBvSHFuVGNSVlVKS2RXb2xJRU5tYVVtdG1UZFVicVYyNGJMa1RtZQpiWHZQdlF3LzJoVk5VVmhWbDNjays1SUZBS0hYVWJ3ZklSWE8vUVlUbFM0ZVdabkFsN0JQSzJQa080SXkvOG1zQVZKRGl4CmkvVm1oaTBYb05lSmxERU9sdzNaY084aTlRZjVSbTNEWmRHUDRha0JsYmk5ekdBWUpqRGFjM0dWdTMxK2pJVG9hUHplbysKeUFDL2svM0J5Slg4enQ1cDRHVXpsNVFKcEVHMnBpQXdJeElKZS8yK3pBMXU5dmhma0FBQURCQU5NZHdhemx5MXNpd0dXbQpJWSs4VFZMN1EwQ1pFTWxTL0VraE1YM2FNQnZYaURXd2cwVk8zKytXUDhlMWhDSUxvNmdqL0N2dFdLdGEzVlozUWFScHZ5CkhCVEp4Q205NHZQOXFPelhTRGZ0WVRrSHh1SFdQaklhb010N0YyL0srejJiZTdESmhvL0ZwMVY0U2x2R1ljWHdqaWhEaDAKbHF1bUltOEJJei9taHpjZTFKR0VMUUdJeXk4RDI0dTNtY2NhSFoxYWY1V3A5Y1VCZ09POXEwa3B1WVhEdHpPSk9UTVozUQpNUm5xdXVVM1ppRHdmRGltZzdsZktwWGkxZzFxeWZUd0FBQU1FQXpoWEdhTVdBM1pUT1hqWWhPTUhkdTk0R2RNcHNXYWo0CjBsMmZ6YzdFWTlzWEdLZ01XMllvRXk5UVNSTDRPUmNMaUFKTDRLZGdZeGZzeVdma1U1d21TbGZXNjlrb0R2WTE0LzNWbWYKZ0NTUkxvL0RnTUZtOGFNK3pUVzhWYTVpclJXWFpEeHNXb0RiNzdIZ2JZaE90M29iOEFWWUh4akk3N1k3MXlBUzhXS2xRSQpYQi9qZ01vN1BCL3BTMVVYSEhCcndxQkdwM3M5aThab0E0L2hLY0pvaEtWSDZGL0Z2Rk1jWHZTNjZOcGNUWHNWQzBVUzNkCkJVY0taNTVvUUhVcnNQQUFBQUdIQnlZWFJvYVd0eVFFeEJVRlJQVUMxU00wZFVUa2xDVXdFQwotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K', + 'ssh_known_hosts': 'Z2l0b3BzLWJpdGJ1Y2tldC10ZXN0LXNlcnZlci5lYXN0dXMuY2xvdWRhcHAuYXp1cmUuY29tIHNzaC1yc2EgQUFBQUIzTnphQzF5YzJFQUFBQURBUUFCQUFBQkFRQytNT0w3bjk2aGs3emVmMDNwak9vMGF3UENISkZ4NU04TjJ2L2tvODgvc202Y2VzOFljdnYyL0hoUlhRSFZHRUxqZjNuTXVGSVJPMEdMdTFabFNreGRUTUhGcXBxYzFjcUM2R3kveUJXRGM1SWFwWnJBMXFxeSsrZVdpelAzQXdMbWsrMUhXWGdtcHljZUtYNU9vd3VNT3cwd3RYRUdTcDhtVk0wV2VpUzEwWnZ5ZVVKK04zbkNvczMyWDhIeVpnc1pMUS9zSTB4NXN6ODQ2am5JZEFOckZsYU9MUTJ1ejRUa0M2ekNvd3lIdzlLWXJ5V2hJZDAraCt5SXQ5dUtqVHZsWFNpdm1ISjViZzdUWWlkbnFtbjI0UGE4WnFpbTE5UGszUjg0cW9qclVmYm1XT3VwUjdYNXZVVWZqYzhERFRxa3FnRmkxcWdVdE1mWGlMRXErZFVa' + }) + + # Check that the configuration does not already exist + with self.assertRaises(ResourceNotFoundError): + self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}') + + # Create a configuration + self.cmd(''' k8s-configuration create -g {rg} + -n {name} + -c {cluster_name} + -u {repo_url} + --cluster-type {cluster_type} + --scope {scope} + --operator-instance-name {operator_instance_name} + --operator-namespace {operator_namespace} + --operator-params \"--git-readonly \" + --ssh-private-key {ssh_private_key} + --ssh-known-hosts {ssh_known_hosts} + --enable-helm-operator + --helm-operator-chart-version 1.2.0 + --helm-operator-params \"--set git.ssh.secretName=gitops-privatekey-{operator_instance_name} --set tillerNamespace=kube-system\" ''', + checks=[ + self.check('name', '{name}'), + self.check('resourceGroup', '{rg}'), + self.check('operatorInstanceName', '{operator_instance_name}'), + self.check('operatorNamespace', '{operator_namespace}'), + self.check('provisioningState', 'Succeeded'), + self.check('operatorScope', 'namespace'), + self.check('operatorType', 'Flux'), + self.check('sshKnownHostsContents', '{ssh_known_hosts}') + ]) + + # Get the configuration created + self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}', + checks=[ + self.check('name', '{name}'), + self.check('resourceGroup', '{rg}'), + self.check('operatorInstanceName', '{operator_instance_name}'), + self.check('operatorNamespace', '{operator_namespace}'), + self.check('provisioningState', 'Succeeded'), + self.check('operatorScope', 'namespace'), + self.check('operatorType', 'Flux'), + self.check('sshKnownHostsContents', '{ssh_known_hosts}') + ]) + + # Delete the created configuration + self.cmd('k8s-configuration delete -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type} -y') + + # -------------------------------------------------------------------- + # HTTPS SCENARIO TEST + # -------------------------------------------------------------------- + self.kwargs.update({ + 'name': 'cli-test-config11', + 'cluster_name': 'nanthicluster0923', + 'rg': 'nanthirg0923', + 'repo_url': 'https://github.com/jonathan-innis/helm-operator-get-started-private.git', + 'operator_instance_name': 'cli-test-config11-opin', + 'operator_namespace': 'cli-test-config11-opns', + 'cluster_type': 'connectedClusters', + 'scope': 'namespace', + 'https_user': 'fake-username', + 'https_key': 'fakepasswordthatiwoulduseforgithub' + }) + + # Check that the configuration does not already exist + with self.assertRaises(ResourceNotFoundError): + self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}') + + self.cmd(''' k8s-configuration create -g {rg} + -n {name} + -c {cluster_name} + -u {repo_url} + --cluster-type {cluster_type} + --scope {scope} + --operator-instance-name {operator_instance_name} + --operator-namespace {operator_namespace} + --operator-params \"--git-readonly \" + --https-user {https_user} + --https-key {https_key} + --enable-helm-operator + --helm-operator-chart-version 1.2.0 + --helm-operator-params \"--set tillerNamespace=kube-system\" ''', + checks=[ + self.check('name', '{name}'), + self.check('resourceGroup', '{rg}'), + self.check('operatorInstanceName', '{operator_instance_name}'), + self.check('operatorNamespace', '{operator_namespace}'), + self.check('provisioningState', 'Succeeded'), + self.check('operatorScope', 'namespace'), + self.check('operatorType', 'Flux') + ]) + + # Get the configuration created + self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}', + checks=[ + self.check('name', '{name}'), + self.check('resourceGroup', '{rg}'), + self.check('operatorInstanceName', '{operator_instance_name}'), + self.check('operatorNamespace', '{operator_namespace}'), + self.check('provisioningState', 'Succeeded'), + self.check('operatorScope', 'namespace'), + self.check('operatorType', 'Flux'), + ]) + + # Delete the created configuration + self.cmd('k8s-configuration delete -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type} -y') diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_validators.py b/src/k8s-config/azext_k8s_config/tests/latest/test_validators.py new file mode 100644 index 00000000000..4e6259d8bf9 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/tests/latest/test_validators.py @@ -0,0 +1,176 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import unittest +import base64 +from azure.cli.core.azclierror import InvalidArgumentValueError, MutuallyExclusiveArgumentError +from azext_k8s_configuration.custom import _get_protected_settings +import azext_k8s_configuration._validators as validators +from Crypto.PublicKey import RSA, ECC, DSA +from paramiko.ed25519key import Ed25519Key + + +class TestValidateKeyTypes(unittest.TestCase): + def test_bad_private_key(self): + private_key_encoded = base64.b64encode("this is not a valid private key".encode('utf-8')).decode('utf-8') + err = "Error! --ssh-private-key provided in invalid format" + with self.assertRaises(InvalidArgumentValueError) as cm: + _get_protected_settings(private_key_encoded, '', '', '') + self.assertEqual(str(cm.exception), err) + + def test_rsa_private_key(self): + rsa_key = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFZRUF1bVA5M09qRHdjdlEyZHZhRlJNNWYrMEhVSnFvOFJnbmdwaGN3NFZidnd1TVNoQTZFc2FyCjFsam1CNUNnT1NGNHJqNDIvcmdxMW1hWndoSUgvckdPSElNa0lIcjFrZmNKMnBrR3ZhK1NxVm4wWUhzMjBpUW02ay92ZXQKdXdVQ2J1QjlxSU5zL2h2b0ppQ21JMUVpVWZ4VGoxRFJCUG15OXR3Qm52bW5FS1kxZ2NhT2YrS2Y1aGhCc09pd00yZnBRTwp0aTlIcHVzM1JhNXpFeElWbjJzVitpRjVvV3ZZM1JQTTlKNXFPMXRObUtOWll6TjgzbDYxMlBzRmR1Vm1QM2NUUlJtK2pzCjdzZW5jY0U0RitzU0hQMlJpMk5DU0JvZ2RJOFR5VTlzeTM3Szl3bFJ5NGZkWWI1K1o3YUZjMjhTNDdDWlo5dTRFVXdWUEYKbjU4dTUzajU0empwdXNpei9ZWmx3MG5NeEQ5SXI0aHlJZ2s0NlUzVmdHR0NPUytZVTVZT2JURGhPRG5udk5VRkg2NVhCagpEM3l6WVJuRDA3b2swQ1JUR3RCOWMzTjBFNDBjUnlPeVpEQ0l5a0FPdHZXYnBUZzdnaXA2UDc4K2pLVlFnanFwRTVQdi9ICnl1dlB6cUJoUkpWcG5VR1dvWnFlcWJhd2N5RWZwdHFLaTNtWUdVMHBBQUFGa0U5cUs3SlBhaXV5QUFBQUIzTnphQzF5YzIKRUFBQUdCQUxwai9kem93OEhMME5uYjJoVVRPWC90QjFDYXFQRVlKNEtZWE1PRlc3OExqRW9RT2hMR3E5Wlk1Z2VRb0RraAplSzQrTnY2NEt0Wm1tY0lTQi82eGpoeURKQ0I2OVpIM0NkcVpCcjJ2a3FsWjlHQjdOdElrSnVwUDczcmJzRkFtN2dmYWlECmJQNGI2Q1lncGlOUklsSDhVNDlRMFFUNXN2YmNBWjc1cHhDbU5ZSEdqbi9pbitZWVFiRG9zRE5uNlVEcll2UjZick4wV3UKY3hNU0ZaOXJGZm9oZWFGcjJOMFR6UFNlYWp0YlRaaWpXV016Zk41ZXRkajdCWGJsWmo5M0UwVVp2bzdPN0hwM0hCT0JmcgpFaHo5a1l0alFrZ2FJSFNQRThsUGJNdCt5dmNKVWN1SDNXRytmbWUyaFhOdkV1T3dtV2ZidUJGTUZUeForZkx1ZDQrZU00CjZicklzLzJHWmNOSnpNUS9TSytJY2lJSk9PbE4xWUJoZ2prdm1GT1dEbTB3NFRnNTU3elZCUit1VndZdzk4czJFWnc5TzYKSk5Ba1V4clFmWE56ZEJPTkhFY2pzbVF3aU1wQURyYjFtNlU0TzRJcWVqKy9Qb3lsVUlJNnFST1Q3L3g4cnJ6ODZnWVVTVgphWjFCbHFHYW5xbTJzSE1oSDZiYWlvdDVtQmxOS1FBQUFBTUJBQUVBQUFHQkFMaElmSXFacUZKSFRXcllyN24rays4alR3ClFtcGJvWmc1YmZSWGdhdGljaEo4ZGlXOGlNblFFRVRBcFd0OU5FZ0tqbDRrSGRuSnoyUERkZzFIN0ExaHppbkNsdzZMTTAKYUkyMGxyR2NrWWpXNDRNd3ozYmRQNHlURTllSXRiM0pmN1pNSGpqek4rSy96bWN0eWdMeXFZSzVXYTljM1JnMXdIRWFNNAplakUvNDg4M25WUmJvSFJDcjFCVi8wQVVFTTZhNisrRHpVZW9WdWdWL3RsV3RVMlJuQlZ4eCtJS0FVSDZRTHJFU2JkUkRoCkVGUEFhRWtEb3crd3dDcFpqTXBhMHdRZXBDSkhwWkJLN1pBU25EU3R3Y2RKRE4yeHZzdVNOOGg0bkN0MlZWd0xRenJKeVAKU2VjcWM3M1hIc3E3VWx6ZU5veHlTVW9KZ2JjNTZoRzhWYS9ITlhsOUtkdkFlWUVzS1l1OW5NRUprVSt3VHo1KzUvM2wwVQpxSkErb0pTVTducjYydlVKQnljbXg0SFdBcjJ6QkR2QnFBUWMzRG9LWHczeVM1Z0c5Zkc0c25OUUkxOHVRSjdOSjdndHZHClpKRU56bTNJMmFTMzl5dndWZnFIMXpXVERxU2VNeWhYeWFnTkFEcGtCVEJIMVJQR2NtTFplclFmWWx1djVVUmFNTXdRQUEKQU1BdE9oNHFwUUhidm5tQ1RVakx4dXRrWnRaRlhNa0hmSTk5NS9Nd2RvWVY1eWRKV0pUVGsyKzB1QVBIcTZEejk2b3dWbQpjUkF2WDBDOVU5d3ZRMkpnR0Y1MDZzcmgzZkVpUzM2d1ArOFd0RjZ6ODd0enJwQnpQVHIxOGRONURCOEx5L3dXRk5BVTdqClBUbXM0dHlUY1VsRXR3eEt4TXJTNC9ROUZwMWozL3JNdnNZdGVaSVgycmN4YUhkWWJDVGJtTUpZS3lVTWVXTk56NXpub1EKcFcyd2NDSmpJc1MvS1F2WmR4cHZwNWd0RXE1WlEva3FvLzJVRWd1NHhwdDNWeUNma0FBQURCQVBOSHVEU1R0ZEpJWjdzcwpaQkVwcUE4TE54b1dMQ2RURnlpRERiUnpYOWVPTldkRFQ3NklaRE9HejczNXJhZUFSM2FiY0FhaUM0dDQwTFJTNGEyN29sCm9wK1dSak9wcjVNYUtOUnk4MCt6VWw3WUlSMjErKzVnMFVnNkRnQlBEdmFJSHFSTnRsZ2gyVXdTL0cva1lOaUlEY0JiS1EKOUcvdTI4ekRIRUtNL21YYS8wYnFtSm16ZUYvY1BLdHdScFE3clFoRnAwUkdFcnZtc0l4dDl6K0ZZZUdncjFBYUVTV0ZlTApmUmZsa0lnOVBWOEl0b09GN25qK2VtMkxkNTNCS1hSUUFBQU1FQXhDTFBueHFFVEsyMW5QOXFxQVYzMEZUUkhGNW9kRHg4ClpiYnZIbjgwdEgxQjYwZjRtTGJFRm56REZFR0NwS2Rwb3dyUXR6WUhnQzNBaGNJUE9BbXFXaDg0UEFPbisreHhFanNaQkwKRWhVWmNFUndkYTMzTnJDNTVEMzZxbDBMZEsrSGRuZUFzVGZhazh0bWVlOTJWb0RxdWovNGFSMjBmUTBJUFVzMU8rWHNRNQpGWVFYQzZndExHZGRzRVFoSDF6MTh6RGtWa1UwdEhlZkJaL2pFZXBiOEZScXoxR1hpT0hGK2xBZVE2b3crS0xlcWtCcXQ4CkZxMHhGdG90SlF4VnFWQUFBQUYycHZhVzV1YVhOQVJFVlRTMVJQVUMxUVRWVkdVRFpOQVFJRAotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K" + protected_settings = _get_protected_settings(rsa_key, '', '', '') + self.assertEqual('sshPrivateKey' in protected_settings, True) + self.assertEqual(protected_settings.get('sshPrivateKey'), rsa_key) + + def test_dsa_private_key(self): + key = DSA.generate(2048) + private_key_encoded = base64.b64encode(key.export_key()).decode('utf-8') + protected_settings = _get_protected_settings(private_key_encoded, '', '', '') + self.assertEqual('sshPrivateKey' in protected_settings, True) + self.assertEqual(protected_settings.get('sshPrivateKey'), private_key_encoded) + + def test_ecdsa_private_key(self): + ecdsa_key = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFhQUFBQUJObFkyUnpZUwoxemFHRXlMVzVwYzNSd01qVTJBQUFBQ0c1cGMzUndNalUyQUFBQVFRUjBRc1BjWmJKeWZPaXE2a1M1d0VaeE5DbmR2YVJHCm1ETEUvVVBjakpDTDZQTVIyZmdPS2NnWlhzTEZkTUFzSnExS2d6TmNDN0ZXNGE0L0wrYTFWWUxDQUFBQXNIZ1RqTFY0RTQKeTFBQUFBRTJWalpITmhMWE5vWVRJdGJtbHpkSEF5TlRZQUFBQUlibWx6ZEhBeU5UWUFBQUJCQkhSQ3c5eGxzbko4NktycQpSTG5BUm5FMEtkMjlwRWFZTXNUOVE5eU1rSXZvOHhIWitBNHB5Qmxld3NWMHdDd21yVXFETTF3THNWYmhyajh2NXJWVmdzCklBQUFBZ0h1U3laU0NUZzJZbVNpOG9aY2c0cnVpODh0T1NUSm1aRVhkR09hdExySHNBQUFBWGFtOXBibTVwYzBCRVJWTkwKVkU5UUxWQk5WVVpRTmswQgotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K" + protected_settings = _get_protected_settings(ecdsa_key, '', '', '') + self.assertEqual('sshPrivateKey' in protected_settings, True) + self.assertEqual(protected_settings.get('sshPrivateKey'), ecdsa_key) + + def test_ed25519_private_key(self): + ed25519_key = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFNd0FBQUF0emMyZ3RaVwpReU5UVXhPUUFBQUNCNjF0RzkrNGFmOTZsWGoyUStjWjJMT2JpV1liMlRtWVR6N3NSV0JDM1hVZ0FBQUtCRzFWRWZSdFZSCkh3QUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQjYxdEc5KzRhZjk2bFhqMlErY1oyTE9iaVdZYjJUbVlUejdzUldCQzNYVWcKQUFBRURRTStLcCtOSWpJVUhSUklqRFE5VDZ0U0V0SG9Ic0w1QjlwbHpCNlZ2MnluclcwYjM3aHAvM3FWZVBaRDV4bllzNQp1SlpodlpPWmhQUHV4RllFTGRkU0FBQUFGMnB2YVc1dWFYTkFSRVZUUzFSUFVDMVFUVlZHVURaTkFRSURCQVVHCi0tLS0tRU5EIE9QRU5TU0ggUFJJVkFURSBLRVktLS0tLQo=" + protected_settings = _get_protected_settings(ed25519_key, '', '', '') + self.assertEqual('sshPrivateKey' in protected_settings, True) + self.assertEqual(protected_settings.get('sshPrivateKey'), ed25519_key) + + +class TestValidateK8sNaming(unittest.TestCase): + def test_long_operator_namespace(self): + operator_namespace = "thisisaverylongnamethatistoolongtobeused" + namespace = OperatorNamespace(operator_namespace) + err = 'Error! Invalid --operator-namespace' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_operator_namespace(namespace) + self.assertEqual(str(cm.exception), err) + + def test_long_operator_instance_name(self): + operator_instance_name = "thisisaverylongnamethatistoolongtobeused" + namespace = OperatorInstanceName(operator_instance_name) + err = 'Error! Invalid --operator-instance-name' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_operator_instance_name(namespace) + self.assertEqual(str(cm.exception), err) + + def test_caps_operator_namespace(self): + operator_namespace = 'Myoperatornamespace' + namespace = OperatorNamespace(operator_namespace) + err = 'Error! Invalid --operator-namespace' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_operator_namespace(namespace) + self.assertEqual(str(cm.exception), err) + + def test_caps_operator_instance_name(self): + operator_instance_name = 'Myoperatorname' + namespace = OperatorInstanceName(operator_instance_name) + err = 'Error! Invalid --operator-instance-name' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_operator_instance_name(namespace) + self.assertEqual(str(cm.exception), err) + + def test_long_config_name(self): + config_name = "thisisaverylongnamethatistoolongtobeusedthisisaverylongnamethatistoolongtobeused" + err = 'Error! Invalid --name' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_configuration_name(config_name) + self.assertEqual(str(cm.exception), err) + + def test_valid_config_name(self): + config_name = "this-is-a-valid-config" + validators._validate_configuration_name(config_name) + + def test_caps_config_name(self): + config_name = "ThisIsaCapsConfigName" + err = 'Error! Invalid --name' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_configuration_name(config_name) + self.assertEqual(str(cm.exception), err) + + def test_dot_config_name(self): + config_name = "a234567890b234567890c234567890d234567890e234567890f234567890.23" + err = 'Error! Invalid --name' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_configuration_name(config_name) + self.assertEqual(str(cm.exception), err) + + def test_end_hyphen_config_name(self): + config_name = "a234567890b234567890c234567890d234567890e234567890f23456789023-" + err = 'Error! Invalid --name' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_configuration_name(config_name) + self.assertEqual(str(cm.exception), err) + + +class TestValidateURLWithParams(unittest.TestCase): + def test_ssh_private_key_with_ssh_url(self): + validators._validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', True, False, False) + + def test_ssh_known_hosts_with_ssh_url(self): + validators._validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', False, True, False) + + def test_https_auth_with_https_url(self): + validators._validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', False, False, True) + + def test_ssh_private_key_with_https_url(self): + err = 'Error! An --ssh-private-key cannot be used with an http(s) url' + with self.assertRaises(MutuallyExclusiveArgumentError) as cm: + validators._validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', True, False, False) + self.assertEqual(str(cm.exception), err) + + def test_ssh_known_hosts_with_https_url(self): + err = 'Error! --ssh-known-hosts cannot be used with an http(s) url' + with self.assertRaises(MutuallyExclusiveArgumentError) as cm: + validators._validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', False, True, False) + self.assertEqual(str(cm.exception), err) + + def test_https_auth_with_ssh_url(self): + err = 'Error! https auth (--https-user and --https-key) cannot be used with a non-http(s) url' + with self.assertRaises(MutuallyExclusiveArgumentError) as cm: + validators._validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', False, False, True) + self.assertEqual(str(cm.exception), err) + + +class TestValidateKnownHosts(unittest.TestCase): + def test_valid_known_hosts(self): + known_hosts_raw = "ssh.dev.azure.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4NakVyIzf1rXYd4d7wo6jBlkLvCA4odBlL0mDUyZ0/QUfTTqeu+tm22gOsv+VrVTMk6vwRU75gY/y9ut5Mb3bR5BV58dKXyq9A9UeB5Cakehn5Zgm6x1mKoVyf+FFn26iYqXJRgzIZZcZ5V6hrE0Qg39kZm4az48o0AUbf6Sp4SLdvnuMa2sVNwHBboS7EJkm57XQPVU3/QpyNLHbWDdzwtrlS+ez30S3AdYhLKEOxAG8weOnyrtLJAUen9mTkol8oII1edf7mWWbWVf0nBmly21+nZcmCTISQBtdcyPaEno7fFQMDD26/s0lfKob4Kw8H" + known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') + validators._validate_known_hosts(known_hosts_encoded) + + def test_valid_known_hosts_with_comment(self): + known_hosts_raw = "ssh.dev.azure.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4NakVyIzf1rXYd4d7wo6jBlkLvCA4odBlL0mDUyZ0/QUfTTqeu+tm22gOsv+VrVTMk6vwRU75gY/y9ut5Mb3bR5BV58dKXyq9A9UeB5Cakehn5Zgm6x1mKoVyf+FFn26iYqXJRgzIZZcZ5V6hrE0Qg39kZm4az48o0AUbf6Sp4SLdvnuMa2sVNwHBboS7EJkm57XQPVU3/QpyNLHbWDdzwtrlS+ez30S3AdYhLKEOxAG8weOnyrtLJAUen9mTkol8oII1edf7mWWbWVf0nBmly21+nZcmCTISQBtdcyPaEno7fFQMDD26/s0lfKob4Kw8H ThisIsAValidComment" + known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') + validators._validate_known_hosts(known_hosts_encoded) + + def test_valid_known_hosts_with_comment_own_line(self): + known_hosts_raw = "#this is a comment on its own line\nssh.dev.azure.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4NakVyIzf1rXYd4d7wo6jBlkLvCA4odBlL0mDUyZ0/QUfTTqeu+tm22gOsv+VrVTMk6vwRU75gY/y9ut5Mb3bR5BV58dKXyq9A9UeB5Cakehn5Zgm6x1mKoVyf+FFn26iYqXJRgzIZZcZ5V6hrE0Qg39kZm4az48o0AUbf6Sp4SLdvnuMa2sVNwHBboS7EJkm57XQPVU3/QpyNLHbWDdzwtrlS+ez30S3AdYhLKEOxAG8weOnyrtLJAUen9mTkol8oII1edf7mWWbWVf0nBmly21+nZcmCTISQBtdcyPaEno7fFQMDD26/s0lfKob4Kw8H" + known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') + validators._validate_known_hosts(known_hosts_encoded) + + def test_invalid_known_hosts(self): + known_hosts_raw = "thisisabadknownhostsfilethatisaninvalidformat" + known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') + err = 'Error! ssh known_hosts provided in wrong format' + with self.assertRaises(InvalidArgumentValueError) as cm: + validators._validate_known_hosts(known_hosts_encoded) + self.assertEqual(str(cm.exception), err) + + +class OperatorNamespace: + def __init__(self, operator_namespace): + self.operator_namespace = operator_namespace + + +class OperatorInstanceName: + def __init__(self, operator_instance_name): + self.operator_instance_name = operator_instance_name diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 627fc091b72..6316977da0e 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -62,16 +62,13 @@ def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, ht def read_config_settings_file(file_path): try: - config_file = open(file_path,) - settings = json.load(config_file) - except ValueError: - raise Exception("File {} is not a valid JSON file".format(file_path)) - - files = len(settings) - if files == 0: - raise Exception("File {} is empty".format(file_path)) - - return settings + with open(file_path, 'r') as f: + settings = json.load(f) + if len(settings) == 0: + raise Exception("File {} is empty".format(file_path)) + return settings + except ValueError as ex: + raise Exception("File {} is not a valid JSON file".format(file_path)) from ex def read_key_file(path): @@ -125,4 +122,15 @@ def fix_compliance_state(config): elif config.compliance_status.compliance_state.lower() == 'compliant': config.compliance_status.compliance_state = 'Installed' - return config \ No newline at end of file + return config + + +def get_parent_api_version(cluster_rp): + if cluster_rp == 'Microsoft.Kubernetes': + return '2020-01-01-preview' + if cluster_rp == 'Microsoft.ResourceConnector': + return '2020-09-15-privatepreview' + if cluster_rp == 'Microsoft.ContainerService': + return '2017-07-01' + raise InvalidArgumentValueError("Error! Cluster RP '{}' is not supported" + " for extension identity".format(cluster_rp)) diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index 68d2dec394a..e4d01b992a3 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -24,6 +24,7 @@ logger = get_logger(__name__) + # Parameter-Level Validation def validate_configuration_type(configuration_type): if configuration_type.lower() != 'sourcecontrolconfiguration': @@ -173,8 +174,8 @@ def validate_known_hosts(knownhost_data): knownhost_str = from_base64(knownhost_data).decode('utf-8') except Exception as ex: raise InvalidArgumentValueError( - consts.SSH_BASE64_ENCODING_ERROR, - consts.SSH_BASE64_ENCODING_HELP) from ex + consts.KNOWN_HOSTS_BASE64_ENCODING_ERROR, + consts.KNOWN_HOSTS_BASE64_ENCODING_HELP) from ex lines = knownhost_str.split('\n') for line in lines: line = line.strip(' ') @@ -209,11 +210,11 @@ def validate_private_key(ssh_private_key_data): key_obj = io.StringIO(from_base64(ssh_private_key_data).decode('utf-8')) Ed25519Key(file_obj=key_obj) return - except SSHException: + except SSHException as ex: raise InvalidArgumentValueError( consts.SSH_PRIVATE_KEY_ERROR, consts.SSH_PRIVATE_KEY_HELP - ) + ) from ex # pylint: disable=broad-except @@ -223,6 +224,35 @@ def validate_cc_registration(cmd): registration_state = rp_client.get(consts.CC_PROVIDER_NAMESPACE).registration_state if registration_state.lower() != consts.REGISTERED.lower(): - logger.warning(consts.CC_REGISTRATION_WARNING.format(consts.CC_PROVIDER_NAMESPACE, consts.CC_REGISTRATION_LINK)) + logger.warning(consts.CC_REGISTRATION_WARNING, + consts.CC_PROVIDER_NAMESPACE, + consts.CC_REGISTRATION_LINK) except Exception: - logger.warning(consts.CC_REGISTRATION_ERROR.format(consts.CC_PROVIDER_NAMESPACE)) + logger.warning(consts.CC_REGISTRATION_ERROR, + consts.CC_PROVIDER_NAMESPACE) + + +def validate_scope_and_namespace(scope, release_namespace, target_namespace): + if scope == 'cluster': + if target_namespace is not None: + message = "When --scope is 'cluster', --target-namespace must not be given." + raise MutuallyExclusiveArgumentError(message) + else: + if release_namespace is not None: + message = "When --scope is 'namespace', --release-namespace must not be given." + raise MutuallyExclusiveArgumentError(message) + + +def validate_scope_after_customization(scope_obj): + if scope_obj is not None and scope_obj.namespace is not None and scope_obj.namespace.target_namespace is None: + message = "When --scope is 'namespace', --target-namespace must be given." + raise RequiredArgumentMissingError(message) + + +def validate_version_and_auto_upgrade(version, auto_upgrade_minor_version): + if version is not None: + if auto_upgrade_minor_version: + message = "To pin to specific version, auto-upgrade-minor-version must be set to 'false'." + raise MutuallyExclusiveArgumentError(message) + + auto_upgrade_minor_version = False From 605d1705bb74943b5c760257d58521ef01c18d35 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 22 Jul 2021 16:11:31 -0700 Subject: [PATCH 29/61] Update codeowners file --- .github/CODEOWNERS | 2 ++ .../partner_extensions/DefaultExtensionWithIdentity.py | 6 ++++++ .../azext_k8s_config/providers/FluxConfigurationProvider.py | 4 ++-- src/k8s-config/setup.py | 6 ++---- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 606a16aaedf..192564982bc 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -128,6 +128,8 @@ /src/k8s-configuration/ @NarayanThiru @jonathan-innis +/src/k8s-config/ @NarayanThiru @jonathan-innis + /src/k8s-extension/ @NarayanThiru @jonathan-innis /src/log-analytics-solution/ @zhoxing-ms diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py index aeb83028c52..67ba409d0d1 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py @@ -45,3 +45,9 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t configuration_protected_settings=configuration_protected_settings, ) return extension_instance, name, create_identity + + def Update(self, extension, auto_upgrade_minor_version, release_train, version): + pass + + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): + pass diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index f0bb6500bb9..5aebf498b3a 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -223,11 +223,11 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster found_flux_extension = True break if not found_flux_extension: - logger.info("'Micrsoft.Flux' extension not found on the cluster, installing it now." + logger.warning("'Micrsoft.Flux' extension not found on the cluster, installing it now." " This may take a minute...") self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE).result() - logger.info("'Microsoft.Flux' extension was successfully installed on the cluster") + logger.warning("'Microsoft.Flux' extension was successfully installed on the cluster") def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, ssh_private_key_file, https_user, https_key, diff --git a/src/k8s-config/setup.py b/src/k8s-config/setup.py index 073813e5e8b..d76543f98de 100644 --- a/src/k8s-config/setup.py +++ b/src/k8s-config/setup.py @@ -14,8 +14,6 @@ from distutils import log as logger logger.warn("Wheel is not available, disabling bdist_wheel hook") -# TODO: Confirm this is the right version number you want and it matches your -# HISTORY.rst entry. VERSION = '0.1.0' # The full list of classifiers is available at @@ -32,9 +30,9 @@ 'License :: OSI Approved :: MIT License', ] -# TODO: Add any additional SDK dependencies here DEPENDENCIES = [ - 'azure-cli-core' + "azure-cli-core" + "pycryptodome~=3.9.8" ] with open('README.rst', 'r', encoding='utf-8') as f: From c2e324f52a5ebffee4623e53edd9af03bd3d78ed Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 22 Jul 2021 16:54:17 -0700 Subject: [PATCH 30/61] Validate data before checking cluster compliance --- .../providers/FluxConfigurationProvider.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 5aebf498b3a..18eafbf758e 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -90,9 +90,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None dp_source_kind = "" git_repository = None - self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name) - + # Validate and Create the Data before checking the cluster compataibility if kind == consts.GIT: dp_source_kind = consts.GIT_REPOSITORY git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout, @@ -114,6 +112,9 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None kustomizations=kustomization ) + self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + return self.client.begin_create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) From 5b1156adb58a506a1e485896f113c8aa38719f43 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 22 Jul 2021 16:54:28 -0700 Subject: [PATCH 31/61] No kustomizations warning --- k8s-custom-pipelines.yml | 2 +- src/k8s-config/azext_k8s_config/consts.py | 6 ++++-- src/k8s-config/azext_k8s_config/format.py | 5 +++++ .../partner_extensions/DefaultExtensionWithIdentity.py | 2 +- .../azext_k8s_config/providers/FluxConfigurationProvider.py | 2 +- src/k8s-config/setup.py | 2 +- 6 files changed, 13 insertions(+), 6 deletions(-) diff --git a/k8s-custom-pipelines.yml b/k8s-custom-pipelines.yml index f93c4a8d42c..1c52c1fb5c2 100644 --- a/k8s-custom-pipelines.yml +++ b/k8s-custom-pipelines.yml @@ -140,7 +140,7 @@ stages: displayName: "Build and Publish the Extension Artifact" variables: CLI_REPO_PATH: $(Agent.BuildDirectory)/s - EXTENSION_NAME: "k8s-configuration" + EXTENSION_NAME: "k8s-config" steps: - task: UsePythonVersion@0 displayName: 'Use Python 3.6' diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index a696070a215..ccb14771248 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -22,8 +22,8 @@ REPOSITORY_REF_TOO_MAY_VALUES_ERROR = "Error! Repository reference is invalid" REPOSITORY_REF_TOO_MAY_VALUES_HELP = "Specifying more than one repository ref argument that isn't --branch and --commit is invalid" -GIT_REPOSITORY_REQUIRED_VALUES_MISSING_ERROR = "Error! Git repository kind is missing required value {}" -GIT_REPOSITORY_REQUIRED_VALUES_MISSING_HELP = "Add missing git repository kind and try again" +GIT_REPOSITORY_REQUIRED_VALUES_MISSING_ERROR = "Error! Required property '{}' was not specified for kind 'GitRepository'" +GIT_REPOSITORY_REQUIRED_VALUES_MISSING_HELP = "Add missing required property and try again" INVALID_DURATION_ERROR = "Error! Invalid {0}." INVALID_DURATION_HELP = "Specify a valid ISO8601 duration and try again" @@ -78,6 +78,8 @@ HTTP_URL_NO_AUTH_WARNING = "Warning! https url is being used without https auth params, ensure the repository url provided is not a private repo" +NO_KUSTOMIZATIONS_WARNING = "Warning! No kustomizations were specified for this configuration. The specified source will not be applied to the cluster" + # PROVIDER REGISTRATION ----------------------------------------- CC_REGISTRATION_WARNING = "'Flux Configuration' cannot be used because '%s' provider has not been registered. More details for registering this provider can be found here - %s" diff --git a/src/k8s-config/azext_k8s_config/format.py b/src/k8s-config/azext_k8s_config/format.py index 42075acbb14..941dfa29170 100644 --- a/src/k8s-config/azext_k8s_config/format.py +++ b/src/k8s-config/azext_k8s_config/format.py @@ -55,4 +55,9 @@ def __get_fluxconfig_table_row(result): print(result) return OrderedDict([ ('name', result['name']), + ('provisioningState', result['provisioningState']), + ('syncState', result['syncState']), + ('namespace', result['namespace']), + ('scope', result['scope']), + ('lastSyncedTime', result['lastSyncedTime']), ]) diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py index 67ba409d0d1..d1b134f6349 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py @@ -48,6 +48,6 @@ def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_t def Update(self, extension, auto_upgrade_minor_version, release_train, version): pass - + def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): pass diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 18eafbf758e..df6b6da5f1c 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -225,7 +225,7 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster break if not found_flux_extension: logger.warning("'Micrsoft.Flux' extension not found on the cluster, installing it now." - " This may take a minute...") + " This may take a minute...") self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE).result() logger.warning("'Microsoft.Flux' extension was successfully installed on the cluster") diff --git a/src/k8s-config/setup.py b/src/k8s-config/setup.py index d76543f98de..04db6f944be 100644 --- a/src/k8s-config/setup.py +++ b/src/k8s-config/setup.py @@ -54,5 +54,5 @@ classifiers=CLASSIFIERS, packages=find_packages(), install_requires=DEPENDENCIES, - package_data={'azext_k8s-config': ['azext_metadata.json']}, + package_data={'azext_k8s_config': ['azext_metadata.json']}, ) From fffe96bbb8c1a31ec65ed93c8a5348a3d588a024 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 23 Jul 2021 14:13:51 -0700 Subject: [PATCH 32/61] Fix identity issue in 2020-07-01 --- src/k8s-config/azext_k8s_config/_params.py | 2 +- .../vendored_sdks/v2020_07_01_preview/models/_models.py | 2 +- .../vendored_sdks/v2020_07_01_preview/models/_models_py3.py | 2 +- src/k8s-config/setup.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 876de1ecaa7..e1431dc99e1 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -149,7 +149,7 @@ def load_arguments(self, _): c.argument('force', help='Specify whether to force delete the extension from the cluster.') - with self.argument_context('k8s-config flux-v1 create') as c: + with self.argument_context('k8s-config fluxv1 create') as c: c.argument('repository_url', options_list=['--repository-url', '-u'], help='Url of the source control repository') diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py index ef31b453ddc..315237c6587 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py @@ -310,7 +310,7 @@ class ExtensionInstance(ProxyResource): 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'str'}, 'last_status_time': {'key': 'properties.lastStatusTime', 'type': 'str'}, 'error_info': {'key': 'properties.errorInfo', 'type': 'ErrorDefinition'}, - 'identity': {'key': 'properties.identity', 'type': 'ConfigurationIdentity'}, + 'identity': {'key': 'identity', 'type': 'ConfigurationIdentity'}, } def __init__( diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py index 7d8c10c5306..f749d3d7078 100644 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py +++ b/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py @@ -328,7 +328,7 @@ class ExtensionInstance(ProxyResource): 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'str'}, 'last_status_time': {'key': 'properties.lastStatusTime', 'type': 'str'}, 'error_info': {'key': 'properties.errorInfo', 'type': 'ErrorDefinition'}, - 'identity': {'key': 'properties.identity', 'type': 'ConfigurationIdentity'}, + 'identity': {'key': 'identity', 'type': 'ConfigurationIdentity'}, } def __init__( diff --git a/src/k8s-config/setup.py b/src/k8s-config/setup.py index 04db6f944be..81a80330a8a 100644 --- a/src/k8s-config/setup.py +++ b/src/k8s-config/setup.py @@ -31,7 +31,7 @@ ] DEPENDENCIES = [ - "azure-cli-core" + "azure-cli-core", "pycryptodome~=3.9.8" ] From e892cc41a35eef0b75edff843f5f8dae12e4d721 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 23 Jul 2021 14:56:11 -0700 Subject: [PATCH 33/61] Fix k8s regex --- src/k8s-config/azext_k8s_config/consts.py | 2 +- .../private-preview/AzurePolicy.Tests.ps1 | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index ccb14771248..9eb907f33ed 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -101,7 +101,7 @@ VALID_DURATION_REGEX = r"((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?" VALID_URL_REGEX = r"^(((http|https|ssh)://)|(git@))" -VALID_KUBERNETES_NAME_REGEX = r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" +VALID_KUBERNETES_NAME_REGEX = r"^[a-z0-9]([.\-a-z0-9]*[a-z0-9])?$" GIT = "git" GIT_REPOSITORY = "GitRepository" diff --git a/testing/test/extensions/private-preview/AzurePolicy.Tests.ps1 b/testing/test/extensions/private-preview/AzurePolicy.Tests.ps1 index ea8c3f46cb4..068789254c6 100644 --- a/testing/test/extensions/private-preview/AzurePolicy.Tests.ps1 +++ b/testing/test/extensions/private-preview/AzurePolicy.Tests.ps1 @@ -10,10 +10,10 @@ Describe 'Azure Policy Testing' { } It 'Creates the extension and checks that it onboards correctly' { - $output = az $Env:K8sExtensionName create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType -n $extensionName + $output = az $Env:K8sExtensionName extension create -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters --extension-type $extensionType -n $extensionName $? | Should -BeTrue - $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue $isAutoUpgradeMinorVersion = ($output | ConvertFrom-Json).autoUpgradeMinorVersion @@ -35,7 +35,7 @@ Describe 'Azure Policy Testing' { } It "Performs a show on the extension" { - $output = az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + $output = az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue $output | Should -Not -BeNullOrEmpty } @@ -71,7 +71,7 @@ Describe 'Azure Policy Testing' { } It "Lists the extensions on the cluster" { - $output = az $Env:K8sExtensionName list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $? | Should -BeTrue $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionType } @@ -79,16 +79,16 @@ Describe 'Azure Policy Testing' { } It "Deletes the extension from the cluster" { - az $Env:K8sExtensionName delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + az $Env:K8sExtensionName extension delete -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeTrue # Extension should not be found on the cluster - az $Env:K8sExtensionName show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName + az $Env:K8sExtensionName extension show -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters -n $extensionName $? | Should -BeFalse } It "Performs another list after the delete" { - $output = az $Env:K8sExtensionName list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters + $output = az $Env:K8sExtensionName extension list -c $ENVCONFIG.arcClusterName -g $ENVCONFIG.resourceGroup --cluster-type connectedClusters $extensionExists = $output | ConvertFrom-Json | Where-Object { $_.extensionType -eq $extensionName } $extensionExists | Should -BeNullOrEmpty } From f0e0037164d6d32a63f97381b5ae7c3d934bf341 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 23 Jul 2021 15:26:14 -0700 Subject: [PATCH 34/61] Fix configuration name regex validation --- src/k8s-config/azext_k8s_config/_params.py | 24 +++++++++--- src/k8s-config/azext_k8s_config/consts.py | 14 +++++-- src/k8s-config/azext_k8s_config/validators.py | 39 +++++++++++++++++-- 3 files changed, 66 insertions(+), 11 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index e1431dc99e1..4fe64ed01f6 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -11,7 +11,7 @@ get_three_state_flag, tags_type ) -from .validators import validate_configuration_name, validate_configuration_type, validate_namespace, validate_operator_instance_name, validate_operator_namespace +from .validators import validate_configuration_name, validate_configuration_type, validate_extension_name, validate_fluxconfig_name, validate_namespace, validate_operator_instance_name, validate_operator_namespace from .action import ( KustomizationAddAction, AddConfigurationProtectedSettings, @@ -24,10 +24,6 @@ def load_arguments(self, _): with self.argument_context('k8s-config') as c: c.argument('tags', tags_type) c.argument('location', validator=get_default_location_from_resource_group) - c.argument('name', - options_list=['--name', '-n'], - help='Name of the configuration', - validator=validate_configuration_name) c.argument('cluster_name', options_list=['--cluster-name', '-c'], help='Name of the Kubernetes cluster') @@ -36,6 +32,12 @@ def load_arguments(self, _): arg_type=get_enum_type(['connectedClusters', 'managedClusters']), help='Specify Arc connected clusters or AKS managed clusters.') + with self.argument_context('k8s-config flux') as c: + c.argument('name', + options_list=['--name', '-n'], + help='Name of the flux configuration', + validator=validate_fluxconfig_name) + with self.argument_context('k8s-config flux create') as c: c.argument('scope', options_list=['--scope', '-s'], @@ -103,6 +105,12 @@ def load_arguments(self, _): c.argument('force', help='Specify whether to force delete the flux configuration from the cluster.') + with self.argument_context('k8s-config extension') as c: + c.argument('name', + options_list=['--name', '-n'], + help='Name of the extension', + validator=validate_extension_name) + with self.argument_context('k8s-config extension create') as c: c.argument('scope', arg_type=get_enum_type(['cluster', 'namespace']), @@ -148,6 +156,12 @@ def load_arguments(self, _): with self.argument_context('k8s-config extension delete') as c: c.argument('force', help='Specify whether to force delete the extension from the cluster.') + + with self.argument_context('k8s-config fluxv1') as c: + c.argument('name', + options_list=['--name', '-n'], + help='Name of the configuration', + validator=validate_configuration_type) with self.argument_context('k8s-config fluxv1 create') as c: c.argument('repository_url', diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 9eb907f33ed..bec3070e578 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -37,8 +37,14 @@ INVALID_KUBERNETES_NAME_HYPHEN_ERROR = "Error! Invalid {0}." INVALID_KUBERNETES_NAME_HYPHEN_HELP = "Parameter {0} cannot begin or end with a hyphen." -INVALID_KUBERNETES_NAME_ERROR = "Error! Invalid {0}." -INVALID_KUBERNETES_NAME_HELP = "Parameter {0} can only contain lowercase alphanumeric characters and hyphens" +INVALID_KUBERNETES_NAME_PERIOD_ERROR = "Error! Invalid {0}." +INVALID_KUBERNETES_NAME_PERIOD_HELP = "Parameter {0} cannot begin or end with a period." + +INVALID_KUBERNETES_DNS_NAME_ERROR = "Error! Invalid {0}." +INVALID_KUBERNETES_DNS_NAME_HELP = "Parameter {0} can only contain lowercase alphanumeric characters and hyphens" + +INVALID_KUBERNETES_DNS_SUBDOMAIN_NAME_ERROR = "Error! Invalid {0}." +INVALID_KUBERNETES_DNS_SUBDOMAIN_NAME_HELP = "Parameter {0} can only contain lowercase alphanumeric characters, hyphens, and periods" DUPLICATE_KUSTOMIZATION_NAME_ERROR = "Error! Invalid Kustomization list. Kustomization name {0} duplicated in multiple Kustomization objects" DUPLICATE_KUSTOMIZATION_NAME_HELP = "Ensure that all Kustomization names are unique and try again" @@ -101,7 +107,9 @@ VALID_DURATION_REGEX = r"((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?" VALID_URL_REGEX = r"^(((http|https|ssh)://)|(git@))" -VALID_KUBERNETES_NAME_REGEX = r"^[a-z0-9]([.\-a-z0-9]*[a-z0-9])?$" + +VALID_KUBERNETES_DNS_SUBDOMAIN_NAME_REGEX = r"^[a-z0-9]([.\-a-z0-9]*[a-z0-9])?$" +VALID_KUBERNETES_DNS_NAME_REGEX = r"^[a-z0-9]([.\-a-z0-9]*[a-z0-9])?$" GIT = "git" GIT_REPOSITORY = "GitRepository" diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index e4d01b992a3..c351787c6c5 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -47,6 +47,14 @@ def validate_configuration_name(namespace): __validate_k8s_name(namespace.name, "--name", 63) +def validate_extension_name(namespace): + __validate_k8s_cr_name(namespace.name, "--name", 253) + + +def validate_fluxconfig_name(namespace): + __validate_k8s_cr_name(namespace.name, "--name", 253) + + def validate_operator_namespace(namespace): if namespace.operator_namespace: __validate_k8s_name(namespace.operator_namespace, "--operator-namespace", 23) @@ -73,6 +81,8 @@ def validate_kustomization(values): def validate_kustomization_list(kustomizations): kustomization_names = set() + if len(kustomizations) == 0: + logger.warning(consts.NO_KUSTOMIZATIONS_WARNING) for kustomization in kustomizations: if kustomization.name in kustomization_names: raise InvalidArgumentValueError( @@ -132,15 +142,38 @@ def __validate_k8s_name(param_value, param_name, max_len): consts.INVALID_KUBERNETES_NAME_LENGTH_ERROR.format(param_name), consts.INVALID_KUBERNETES_NAME_LENGTH_HELP.format(param_name, max_len) ) - if not re.match(consts.VALID_KUBERNETES_NAME_REGEX, param_value): + if not re.match(consts.VALID_KUBERNETES_DNS_NAME_REGEX, param_value): + if param_value[0] == "-" or param_value[-1] == "-": + raise InvalidArgumentValueError( + consts.INVALID_KUBERNETES_NAME_HYPHEN_ERROR.format(param_name), + consts.INVALID_KUBERNETES_NAME_HYPHEN_HELP.format(param_name) + ) + raise InvalidArgumentValueError( + consts.INVALID_KUBERNETES_DNS_NAME_ERROR.format(param_name), + consts.INVALID_KUBERNETES_DNS_NAME_HELP.format(param_name) + ) + + +def __validate_k8s_cr_name(param_value, param_name, max_len): + if len(param_value) > max_len: + raise InvalidArgumentValueError( + consts.INVALID_KUBERNETES_NAME_LENGTH_ERROR.format(param_name), + consts.INVALID_KUBERNETES_NAME_LENGTH_HELP.format(param_name, max_len) + ) + if not re.match(consts.VALID_KUBERNETES_DNS_SUBDOMAIN_NAME_REGEX, param_value): if param_value[0] == "-" or param_value[-1] == "-": raise InvalidArgumentValueError( consts.INVALID_KUBERNETES_NAME_HYPHEN_ERROR.format(param_name), consts.INVALID_KUBERNETES_NAME_HYPHEN_HELP.format(param_name) ) + if param_value[0] == "." or param_value[-1] == ".": + raise InvalidArgumentValueError( + consts.INVALID_KUBERNETES_NAME_PERIOD_ERROR.format(param_name), + consts.INVALID_KUBERNETES_NAME_PERIOD_HELP.format(param_name) + ) raise InvalidArgumentValueError( - consts.INVALID_KUBERNETES_NAME_ERROR.format(param_name), - consts.INVALID_KUBERNETES_NAME_HELP.format(param_name) + consts.INVALID_KUBERNETES_DNS_SUBDOMAIN_NAME_ERROR.format(param_name), + consts.INVALID_KUBERNETES_DNS_SUBDOMAIN_NAME_ERROR.format(param_name) ) From 11603c9fd3307c3e0a48673a55249bf4fa9eee81 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 23 Jul 2021 16:13:20 -0700 Subject: [PATCH 35/61] Fix name length validation --- src/k8s-config/azext_k8s_config/_params.py | 26 ++++++++----------- src/k8s-config/azext_k8s_config/consts.py | 9 +++++-- src/k8s-config/azext_k8s_config/format.py | 1 - .../partner_extensions/OpenServiceMesh.py | 6 ----- .../providers/FluxConfigurationProvider.py | 4 +-- src/k8s-config/azext_k8s_config/validators.py | 9 +++++-- 6 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 4fe64ed01f6..9886652d6f8 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -11,7 +11,7 @@ get_three_state_flag, tags_type ) -from .validators import validate_configuration_name, validate_configuration_type, validate_extension_name, validate_fluxconfig_name, validate_namespace, validate_operator_instance_name, validate_operator_namespace +from .validators import validate_configuration_name, validate_extension_name, validate_fluxconfig_name, validate_namespace, validate_operator_instance_name, validate_operator_namespace from .action import ( KustomizationAddAction, AddConfigurationProtectedSettings, @@ -34,9 +34,9 @@ def load_arguments(self, _): with self.argument_context('k8s-config flux') as c: c.argument('name', - options_list=['--name', '-n'], - help='Name of the flux configuration', - validator=validate_fluxconfig_name) + options_list=['--name', '-n'], + help='Name of the flux configuration', + validator=validate_fluxconfig_name) with self.argument_context('k8s-config flux create') as c: c.argument('scope', @@ -107,9 +107,9 @@ def load_arguments(self, _): with self.argument_context('k8s-config extension') as c: c.argument('name', - options_list=['--name', '-n'], - help='Name of the extension', - validator=validate_extension_name) + options_list=['--name', '-n'], + help='Name of the extension', + validator=validate_extension_name) with self.argument_context('k8s-config extension create') as c: c.argument('scope', @@ -156,12 +156,12 @@ def load_arguments(self, _): with self.argument_context('k8s-config extension delete') as c: c.argument('force', help='Specify whether to force delete the extension from the cluster.') - + with self.argument_context('k8s-config fluxv1') as c: c.argument('name', - options_list=['--name', '-n'], - help='Name of the configuration', - validator=validate_configuration_type) + options_list=['--name', '-n'], + help='Name of the configuration', + validator=validate_configuration_name) with self.argument_context('k8s-config fluxv1 create') as c: c.argument('repository_url', @@ -170,10 +170,6 @@ def load_arguments(self, _): c.argument('scope', arg_type=get_enum_type(['namespace', 'cluster']), help='''Specify scope of the operator to be 'namespace' or 'cluster' ''') - c.argument('configuration_type', - validator=validate_configuration_type, - arg_type=get_enum_type(['sourceControlConfiguration']), - help='Type of the configuration') c.argument('enable_helm_operator', arg_group="Helm Operator", arg_type=get_three_state_flag(), diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index bec3070e578..71dcb604e2e 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -46,9 +46,12 @@ INVALID_KUBERNETES_DNS_SUBDOMAIN_NAME_ERROR = "Error! Invalid {0}." INVALID_KUBERNETES_DNS_SUBDOMAIN_NAME_HELP = "Parameter {0} can only contain lowercase alphanumeric characters, hyphens, and periods" -DUPLICATE_KUSTOMIZATION_NAME_ERROR = "Error! Invalid Kustomization list. Kustomization name {0} duplicated in multiple Kustomization objects" +DUPLICATE_KUSTOMIZATION_NAME_ERROR = "Error! Invalid kustomization list. Kustomization name '{0}' duplicated in multiple Kustomization objects" DUPLICATE_KUSTOMIZATION_NAME_HELP = "Ensure that all Kustomization names are unique and try again" +KUSTOMIZATION_NAME_TOO_LONG_ERROR = "Error! Invalid Kustomization list. Flux configuration name '{0}' combined with kustomization name '{1}' cannot be greater than 62 characters" +KUSTOMIZATION_NAME_TOO_LONG_HELP = "Shorten the flux configuration or the kustomization name and try again" + SSH_PRIVATE_KEY_WITH_HTTP_URL_ERROR = "Error! An --ssh-private-key cannot be used with an http(s) url" SSH_PRIVATE_KEY_WITH_HTTP_URL_HELP = "Verify the url provided is a valid ssh url and not an http(s) url" @@ -103,7 +106,7 @@ DEPENDENCY_KEYS = ["dependencies", "depends_on"] SYNC_INTERVAL_KEYS = ["interval", "sync_interval"] TIMEOUT_KEY = "timeout" -REQUIRED_KUSTOMIZATION_KEYS = {"name", "path"} +REQUIRED_KUSTOMIZATION_KEYS = {"name"} VALID_DURATION_REGEX = r"((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?" VALID_URL_REGEX = r"^(((http|https|ssh)://)|(git@))" @@ -119,3 +122,5 @@ MANAGED_RP_NAMESPACE = "Microsoft.ContainerService" CONNECTED_RP_NAMESPACE = "Microsoft.Kubernetes" + +KUBERNETES_MAX_NAME_SIZE = 63 diff --git a/src/k8s-config/azext_k8s_config/format.py b/src/k8s-config/azext_k8s_config/format.py index 941dfa29170..134604435e1 100644 --- a/src/k8s-config/azext_k8s_config/format.py +++ b/src/k8s-config/azext_k8s_config/format.py @@ -52,7 +52,6 @@ def fluxconfig_show_table_format(result): def __get_fluxconfig_table_row(result): - print(result) return OrderedDict([ ('name', result['name']), ('provisioningState', result['provisioningState']), diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py b/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py index d2c95b74588..2622d65c276 100644 --- a/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py +++ b/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py @@ -10,10 +10,6 @@ from knack.log import get_logger from azure.cli.core.azclierror import InvalidArgumentValueError, RequiredArgumentMissingError -from azure.cli.core.commands.client_factory import get_subscription_id - -from packaging import version -import yaml from .PartnerExtensionModel import PartnerExtensionModel @@ -23,8 +19,6 @@ Scope ) -from .._client_factory import cf_resources - logger = get_logger(__name__) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index df6b6da5f1c..534aabb492d 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -100,7 +100,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None local_auth_ref) if kustomization: - validate_kustomization_list(kustomization) + validate_kustomization_list(name, kustomization) flux_configuration = FluxConfiguration( scope=scope, @@ -184,7 +184,7 @@ def create_kustomization(self, resource_group_name, cluster_type, cluster_name, ) proposed_change = flux_configuration.kustomizations[:] + kustomization - validate_kustomization_list(proposed_change) + validate_kustomization_list(name, proposed_change) upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index c351787c6c5..38c97667776 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -52,7 +52,7 @@ def validate_extension_name(namespace): def validate_fluxconfig_name(namespace): - __validate_k8s_cr_name(namespace.name, "--name", 253) + __validate_k8s_cr_name(namespace.name, "--name", 63) def validate_operator_namespace(namespace): @@ -79,7 +79,7 @@ def validate_kustomization(values): ) -def validate_kustomization_list(kustomizations): +def validate_kustomization_list(name, kustomizations): kustomization_names = set() if len(kustomizations) == 0: logger.warning(consts.NO_KUSTOMIZATIONS_WARNING) @@ -89,6 +89,11 @@ def validate_kustomization_list(kustomizations): consts.DUPLICATE_KUSTOMIZATION_NAME_ERROR.format(kustomization.name), consts.DUPLICATE_KUSTOMIZATION_NAME_HELP ) + if len(f"{name}-{kustomization.name}") > consts.KUBERNETES_MAX_NAME_SIZE: + raise InvalidArgumentValueError( + consts.KUSTOMIZATION_NAME_TOO_LONG_ERROR.format(name, kustomization.name), + consts.KUSTOMIZATION_NAME_TOO_LONG_HELP + ) kustomization_names.add(kustomization.name) From e66bf48729d34a95b6d7deb05f751cbcd79b8009 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 27 Jul 2021 15:22:53 -0700 Subject: [PATCH 36/61] Adding some validation warnings --- src/k8s-config/azext_k8s_config/consts.py | 2 +- .../azext_k8s_config/providers/FluxConfigurationProvider.py | 4 ++++ src/k8s-config/azext_k8s_config/validators.py | 2 -- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 71dcb604e2e..3cbeb94481c 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -87,7 +87,7 @@ HTTP_URL_NO_AUTH_WARNING = "Warning! https url is being used without https auth params, ensure the repository url provided is not a private repo" -NO_KUSTOMIZATIONS_WARNING = "Warning! No kustomizations were specified for this configuration. The specified source will not be applied to the cluster" +NO_KUSTOMIZATIONS_WARNING = "Warning! No kustomizations were specified for this configuration. The specified source may not be applied to the cluster." # PROVIDER REGISTRATION ----------------------------------------- diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 534aabb492d..0551ff06504 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -101,6 +101,8 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None if kustomization: validate_kustomization_list(name, kustomization) + else: + logger.warning(consts.NO_KUSTOMIZATIONS_WARNING) flux_configuration = FluxConfiguration( scope=scope, @@ -115,6 +117,8 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + logger.warning("Creating the fluxConfiguration '%s' in the cluster. This may take a minute...", name) + return self.client.begin_create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index 38c97667776..af529048233 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -81,8 +81,6 @@ def validate_kustomization(values): def validate_kustomization_list(name, kustomizations): kustomization_names = set() - if len(kustomizations) == 0: - logger.warning(consts.NO_KUSTOMIZATIONS_WARNING) for kustomization in kustomizations: if kustomization.name in kustomization_names: raise InvalidArgumentValueError( From 0001318b0689c0831f65b1be26e9aa9f0132153a Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 27 Jul 2021 17:31:38 -0700 Subject: [PATCH 37/61] Add protected settings to request --- .../providers/FluxConfigurationProvider.py | 34 +++++++++++++------ 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 0551ff06504..7a3bb68f3f8 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -99,11 +99,19 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None https_key, known_hosts, known_hosts_file, local_auth_ref) + # Do Validations on the Kustomization List if kustomization: validate_kustomization_list(name, kustomization) else: logger.warning(consts.NO_KUSTOMIZATIONS_WARNING) + # Get the protected settings and validate the private key value + protected_settings = get_protected_settings( + ssh_private_key, ssh_private_key_file, https_user, https_key + ) + if consts.SSH_PRIVATE_KEY_KEY in protected_settings: + validate_private_key(protected_settings['sshPrivateKey']) + flux_configuration = FluxConfiguration( scope=scope, namespace=namespace, @@ -111,7 +119,8 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None timeout=timeout, sync_interval=sync_interval, git_repository=git_repository, - kustomizations=kustomization + kustomizations=kustomization, + configuration_protected_settings=protected_settings, ) self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) @@ -145,12 +154,23 @@ def create_source(self, resource_group_name, cluster_type, cluster_name, name, u https_user, https_key, known_hosts, known_hosts_file, local_auth_ref) + + # Get the protected settings and validate the private key value + protected_settings = get_protected_settings( + ssh_private_key, ssh_private_key_file, https_user, https_key + ) + if consts.SSH_PRIVATE_KEY_KEY in protected_settings: + validate_private_key(protected_settings['sshPrivateKey']) + + print(protected_settings) + flux_configuration = FluxConfiguration( scope=scope, namespace=namespace, source_kind=dp_source_kind, git_repository=git_repository, - kustomizations=[] + kustomizations=[], + configuration_protected_settings=protected_settings, ) # cache the payload if --defer used or send to Azure @@ -187,10 +207,11 @@ def create_kustomization(self, resource_group_name, cluster_type, cluster_name, force=force ) - proposed_change = flux_configuration.kustomizations[:] + kustomization + proposed_change = flux_configuration.kustomizations[:] + [kustomization] validate_kustomization_list(name, proposed_change) upsert_to_collection(flux_configuration, 'kustomizations', kustomization, 'name') + flux_configuration.configuration_protected_settings = None flux_configuration = cached_put(self.cmd, self.client.begin_create_or_update, flux_configuration, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, cluster_resource_name=cluster_type, @@ -241,13 +262,6 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time validate_duration("--timeout", timeout) validate_duration("--sync-interval", sync_interval) - # Get the protected settings and validate the private key value - protected_settings = get_protected_settings( - ssh_private_key, ssh_private_key_file, https_user, https_key - ) - if consts.SSH_PRIVATE_KEY_KEY in protected_settings: - validate_private_key(protected_settings['sshPrivateKey']) - # Get the known hosts data and validate it knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file) if knownhost_data: From 4dfa48496b7ebcf60c476d57be0b1be0cb951d20 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 27 Jul 2021 18:21:32 -0700 Subject: [PATCH 38/61] Exclude private test path --- src/k8s-config/azext_k8s_config/_params.py | 152 +++++++++--------- src/k8s-config/azext_k8s_config/commands.py | 4 +- src/k8s-config/azext_k8s_config/consts.py | 4 +- .../providers/FluxConfigurationProvider.py | 1 - testing/Test.ps1 | 15 +- 5 files changed, 91 insertions(+), 85 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 9886652d6f8..4451eb40a0e 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -216,80 +216,80 @@ def load_arguments(self, _): arg_group="Auth", help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') - # with self.argument_context('k8s-config flux source') as c: - # c.argument('scope', - # options_list=['--scope', '-s'], - # arg_type=get_enum_type(['namespace', 'cluster']), - # help="Specify scope of the operator to be 'namespace' or 'cluster'") - # c.argument('namespace', - # help='Namespace to deploy the configuration', - # options_list=['--namespace', '--ns'], - # validator=validate_namespace) - # c.argument('kind', - # arg_type=get_enum_type([consts.GIT]), - # help='Source kind to reconcile') - # c.argument('url', - # options_list=['--url', '-u'], - # help='URL of the source to reconcile') - # c.argument('timeout', - # help='Maximum time to reconcile the source before timing out') - # c.argument('sync_interval', - # options_list=['--interval', '--sync-interval'], - # help='Time between reconciliations of the source on the cluster') - # c.argument('branch', - # arg_group="Repo Ref", - # help='Branch to reconcile with the git source') - # c.argument('tag', - # arg_group="Repo Ref", - # help='Tag to reconcile with the git source') - # c.argument('semver', - # arg_group="Repo Ref", - # help='Semver range to reconcile with the git source') - # c.argument('commit', - # arg_group="Repo Ref", - # help='Specific commit to reconcile with the git source') - # c.argument('ssh_private_key', - # arg_group="Auth", - # help='Base64-encoded private ssh key for private repository sync') - # c.argument('ssh_private_key_file', - # arg_group="Auth", - # help='Filepath to private ssh key for private repository sync') - # c.argument('https_user', - # arg_group="Auth", - # help='HTTPS username for private repository sync') - # c.argument('https_key', - # arg_group="Auth", - # help='HTTPS token/password for private repository sync') - # c.argument('known_hosts', - # arg_group="Auth", - # help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') - # c.argument('known_hosts_file', - # arg_group="Auth", - # help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') - # c.argument('local_auth_ref', - # options_list=['--local-auth-ref'], - # arg_group="Auth", - # help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') + with self.argument_context('k8s-config flux source') as c: + c.argument('scope', + options_list=['--scope', '-s'], + arg_type=get_enum_type(['namespace', 'cluster']), + help="Specify scope of the operator to be 'namespace' or 'cluster'") + c.argument('namespace', + help='Namespace to deploy the configuration', + options_list=['--namespace', '--ns'], + validator=validate_namespace) + c.argument('kind', + arg_type=get_enum_type([consts.GIT]), + help='Source kind to reconcile') + c.argument('url', + options_list=['--url', '-u'], + help='URL of the source to reconcile') + c.argument('timeout', + help='Maximum time to reconcile the source before timing out') + c.argument('sync_interval', + options_list=['--interval', '--sync-interval'], + help='Time between reconciliations of the source on the cluster') + c.argument('branch', + arg_group="Repo Ref", + help='Branch to reconcile with the git source') + c.argument('tag', + arg_group="Repo Ref", + help='Tag to reconcile with the git source') + c.argument('semver', + arg_group="Repo Ref", + help='Semver range to reconcile with the git source') + c.argument('commit', + arg_group="Repo Ref", + help='Specific commit to reconcile with the git source') + c.argument('ssh_private_key', + arg_group="Auth", + help='Base64-encoded private ssh key for private repository sync') + c.argument('ssh_private_key_file', + arg_group="Auth", + help='Filepath to private ssh key for private repository sync') + c.argument('https_user', + arg_group="Auth", + help='HTTPS username for private repository sync') + c.argument('https_key', + arg_group="Auth", + help='HTTPS token/password for private repository sync') + c.argument('known_hosts', + arg_group="Auth", + help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') + c.argument('known_hosts_file', + arg_group="Auth", + help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') + c.argument('local_auth_ref', + options_list=['--local-auth-ref'], + arg_group="Auth", + help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') - # with self.argument_context('k8s-config flux kustomization') as c: - # c.argument('kustomization_name', - # help='Specify the name of the kustomization to add to the configuration') - # c.argument('path', - # help='Specify the path in the source that the kustomization should apply') - # c.argument('dependencies', - # options_list=['--depends', '--dependencies'], - # help='Specify the names of kustomization dependencies') - # c.argument('timeout', - # help='Maximum time to reconcile the kustomization before timing out') - # c.argument('sync_interval', - # options_list=['--interval', '--sync-interval'], - # help='Time between reconciliations of the kustomization on the cluster') - # c.argument('retry_interval', - # help='Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval') - # c.argument('prune', - # help='Whether to garbage collect resources deployed by the kustomization on the cluster') - # c.argument('force', - # help='Whether to re-create resources that cannot be updated on the cluster (i.e. jobs)') - # c.argument('validation', - # arg_type=get_enum_type(['none', 'client', 'server']), - # help='Specify whether to dry-run manifests at the client or at the apiserver level before applying them to the cluster.') + with self.argument_context('k8s-config flux kustomization') as c: + c.argument('kustomization_name', + help='Specify the name of the kustomization to add to the configuration') + c.argument('path', + help='Specify the path in the source that the kustomization should apply') + c.argument('dependencies', + options_list=['--depends', '--dependencies'], + help='Specify the names of kustomization dependencies') + c.argument('timeout', + help='Maximum time to reconcile the kustomization before timing out') + c.argument('sync_interval', + options_list=['--interval', '--sync-interval'], + help='Time between reconciliations of the kustomization on the cluster') + c.argument('retry_interval', + help='Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval') + c.argument('prune', + help='Whether to garbage collect resources deployed by the kustomization on the cluster') + c.argument('force', + help='Whether to re-create resources that cannot be updated on the cluster (i.e. jobs)') + c.argument('validation', + arg_type=get_enum_type(['none', 'client', 'server']), + help='Specify whether to dry-run manifests at the client or at the apiserver level before applying them to the cluster.') diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index b89729f8867..4c8b4a1862f 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -41,8 +41,8 @@ def load_command_table(self, _): g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) g.custom_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) g.custom_command('delete', 'flux_config_delete', confirmation=True) - g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) - g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) + # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) + # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: g.custom_command('create', 'extension_create') diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 3cbeb94481c..2f79dc51f11 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -111,8 +111,8 @@ VALID_DURATION_REGEX = r"((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?" VALID_URL_REGEX = r"^(((http|https|ssh)://)|(git@))" -VALID_KUBERNETES_DNS_SUBDOMAIN_NAME_REGEX = r"^[a-z0-9]([.\-a-z0-9]*[a-z0-9])?$" -VALID_KUBERNETES_DNS_NAME_REGEX = r"^[a-z0-9]([.\-a-z0-9]*[a-z0-9])?$" +VALID_KUBERNETES_DNS_SUBDOMAIN_NAME_REGEX = r"^[a-z0-9]([\.\-a-z0-9]*[a-z0-9])?$" +VALID_KUBERNETES_DNS_NAME_REGEX = r"^[a-z0-9]([\-a-z0-9]*[a-z0-9])?$" GIT = "git" GIT_REPOSITORY = "GitRepository" diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 7a3bb68f3f8..19310f8cdc8 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -154,7 +154,6 @@ def create_source(self, resource_group_name, cluster_type, cluster_name, name, u https_user, https_key, known_hosts, known_hosts_file, local_auth_ref) - # Get the protected settings and validate the private key value protected_settings = get_protected_settings( ssh_private_key, ssh_private_key_file, https_user, https_key diff --git a/testing/Test.ps1 b/testing/Test.ps1 index 1fdc5e4db0d..c9fa58c1856 100644 --- a/testing/Test.ps1 +++ b/testing/Test.ps1 @@ -51,10 +51,9 @@ if ($Type -eq 'k8s-extension') { exit 1 } } + $testFilePath = "$PSScriptRoot/test/extensions" if ($OnlyPublicTests) { - $testFilePath = "$PSScriptRoot/test/extensions/public" - } else { - $testFilePath = "$PSScriptRoot/test/extensions" + $excludePath = "$PSScriptRoot/test/extensions/private" } } elseif ($Type -eq 'k8s-configuration') { $k8sConfigurationVersion = $ENVCONFIG.extensionVersion.'k8s-configuration' @@ -75,11 +74,19 @@ if ($Type -eq 'k8s-extension') { } $Env:K8sExtensionName = "k8s-config" $testFilePath = "$PSScriptRoot/test" + $excludePath = "$PSScriptRoot/test/extensions/private" } if ($CI) { Write-Host "Invoking Pester to run tests from '$testFilePath'..." - $testResult = Invoke-Pester $testFilePath -Passthru -Output Detailed + if ($excludePath) + { + $testResult = Invoke-Pester $testFilePath -Passthru -Output Detailed -ExcludePath $excludePath + } + else + { + $testResult = Invoke-Pester $testFilePath -Passthru -Output Detailed + } $testResult | Export-JUnitReport -Path TestResults.xml } else { if ($Path) { From 918c86dde375b183ea952d9f0e4c141517488b64 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Sat, 7 Aug 2021 15:10:21 -0700 Subject: [PATCH 39/61] Add suspend functionality --- src/k8s-config/azext_k8s_config/_params.py | 2 ++ src/k8s-config/azext_k8s_config/custom.py | 5 +++-- .../azext_k8s_config/providers/FluxConfigurationProvider.py | 5 ++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 4451eb40a0e..b8ae1ce71d7 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -95,6 +95,8 @@ def load_arguments(self, _): options_list=['--local-auth-ref'], arg_group="Auth", help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') + c.argument('suspend', + help='Suspend the reconciliation of the source and kustomizations associated with this configuration') c.argument('kustomization', options_list=['--kustomization', '-k'], action=KustomizationAddAction, diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 3eb43fd6057..c7227ad8cbb 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -58,12 +58,13 @@ def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_n scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None, kustomization=None): + known_hosts_file=None, suspend=False, kustomization=None): provider = FluxConfigurationProvider(cmd) return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, kustomization) + ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, suspend, + kustomization) def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 19310f8cdc8..ba25c9ea0f5 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -83,7 +83,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None, kustomization=None): + known_hosts_file=None, suspend=False, kustomization=None): # Determine the cluster RP cluster_rp = get_cluster_rp(cluster_type) @@ -116,9 +116,8 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None scope=scope, namespace=namespace, source_kind=dp_source_kind, - timeout=timeout, - sync_interval=sync_interval, git_repository=git_repository, + suspend=suspend, kustomizations=kustomization, configuration_protected_settings=protected_settings, ) From 7b2ee2aedac105a04a64e0dc9e9fb33397bf4e66 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 9 Aug 2021 12:53:33 -0700 Subject: [PATCH 40/61] Add correct values to build Kustomization --- src/k8s-config/azext_k8s_config/action.py | 8 +++++++- src/k8s-config/azext_k8s_config/consts.py | 5 +++-- src/k8s-config/azext_k8s_config/validators.py | 8 +++++--- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/action.py b/src/k8s-config/azext_k8s_config/action.py index 90499a27202..38718d22ae8 100644 --- a/src/k8s-config/azext_k8s_config/action.py +++ b/src/k8s-config/azext_k8s_config/action.py @@ -17,6 +17,8 @@ def __call__(self, parser, namespace, values, option_string=None): validate_kustomization(values) dependencies = [] sync_interval = None + retry_interval = None + timeout = None kwargs = {} for item in values: try: @@ -25,6 +27,10 @@ def __call__(self, parser, namespace, values, option_string=None): dependencies = parse_dependencies(value) elif key in consts.SYNC_INTERVAL_KEYS: sync_interval = value + elif key in consts.RETRY_INTERVAL_KEYS: + retry_interval = value + elif key in consts.TIMEOUT_KEYS: + timeout = value else: kwargs[key] = value except ValueError as ex: @@ -33,7 +39,7 @@ def __call__(self, parser, namespace, values, option_string=None): super().__call__( parser, namespace, - KustomizationDefinition(depends_on=dependencies, sync_interval=get_duration(sync_interval), **kwargs), + KustomizationDefinition(depends_on=dependencies, sync_interval_in_seconds=get_duration(sync_interval), retry_interval_in_seconds=get_duration(retry_interval), timeout_in_seconds=get_duration(timeout), **kwargs), option_string ) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 2f79dc51f11..3d23b5a8e98 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -104,8 +104,9 @@ HTTPS_KEY_KEY = "httpsKey" DEPENDENCY_KEYS = ["dependencies", "depends_on"] -SYNC_INTERVAL_KEYS = ["interval", "sync_interval"] -TIMEOUT_KEY = "timeout" +SYNC_INTERVAL_KEYS = ["interval", "sync_interval", "syncInterval"] +RETRY_INTERVAL_KEYS = ["retryInterval", "retry_interval"] +TIMEOUT_KEYS = ["timeout"] REQUIRED_KUSTOMIZATION_KEYS = {"name"} VALID_DURATION_REGEX = r"((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?" diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index af529048233..51f64341ea9 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -66,10 +66,12 @@ def validate_kustomization(values): key, value = item.split('=', 1) if key == "name": __validate_k8s_name(value, key, 63) - elif key == consts.SYNC_INTERVAL_KEYS: - validate_duration("interval", value) - elif key == consts.TIMEOUT_KEY: + elif key in consts.SYNC_INTERVAL_KEYS: + validate_duration("sync-interval", value) + elif key in consts.TIMEOUT_KEYS: validate_duration("timeout", value) + elif key in consts.RETRY_INTERVAL_KEYS: + validate_duration("retry-interval", value) if key in required_keys: required_keys.remove(key) if required_keys: From 91de53a28924574f168400c3293ad862d3e298a4 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 9 Aug 2021 13:21:14 -0700 Subject: [PATCH 41/61] Add no_wait --- src/k8s-config/azext_k8s_config/_params.py | 2 +- src/k8s-config/azext_k8s_config/commands.py | 8 +++--- src/k8s-config/azext_k8s_config/consts.py | 2 +- src/k8s-config/azext_k8s_config/custom.py | 12 ++++----- .../providers/ExtensionProvider.py | 21 ++++++---------- .../providers/FluxConfigurationProvider.py | 25 ++++++++++--------- 6 files changed, 32 insertions(+), 38 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index b8ae1ce71d7..1cb08a3e781 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -92,7 +92,7 @@ def load_arguments(self, _): arg_group="Auth", help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') c.argument('local_auth_ref', - options_list=['--local-auth-ref'], + options_list=['--local-auth-ref', '--local-ref'], arg_group="Auth", help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') c.argument('suspend', diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 4c8b4a1862f..bebdfc32715 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -37,18 +37,18 @@ def load_command_table(self, _): ) with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_preview=True) as g: - g.custom_command('create', 'flux_config_create') + g.custom_command('create', 'flux_config_create', supports_no_wait=True) g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) g.custom_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) - g.custom_command('delete', 'flux_config_delete', confirmation=True) + g.custom_command('delete', 'flux_config_delete', confirmation=True, supports_no_wait=True) # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: - g.custom_command('create', 'extension_create') + g.custom_command('create', 'extension_create', supports_no_wait=True) g.custom_command('list', "extension_list", table_transformer=extension_list_table_format) g.custom_command('show', 'extension_show', table_transformer=extension_show_table_format) - g.custom_command('delete', 'extension_delete', confirmation=True) + g.custom_command('delete', 'extension_delete', confirmation=True, supports_no_wait=True) with self.command_group('k8s-config fluxv1', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client, deprecate_info=self.deprecate(redirect='k8s-config flux')) as g: g.custom_command('create', 'sourcecontrol_create') diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 3d23b5a8e98..36d44dbdf9e 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -103,7 +103,7 @@ HTTPS_USER_KEY = "httpsUser" HTTPS_KEY_KEY = "httpsKey" -DEPENDENCY_KEYS = ["dependencies", "depends_on"] +DEPENDENCY_KEYS = ["dependencies", "depends_on", "dependsOn", "depends"] SYNC_INTERVAL_KEYS = ["interval", "sync_interval", "syncInterval"] RETRY_INTERVAL_KEYS = ["retryInterval", "retry_interval"] TIMEOUT_KEYS = ["timeout"] diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index c7227ad8cbb..c151590b00a 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -58,13 +58,13 @@ def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_n scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None, suspend=False, kustomization=None): + known_hosts_file=None, suspend=False, kustomization=None, no_wait=False): provider = FluxConfigurationProvider(cmd) return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, suspend, - kustomization) + kustomization, no_wait) def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, @@ -90,9 +90,9 @@ def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_t validation, force) -def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False): +def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False): provider = FluxConfigurationProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name, force) + return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait) # Extension Methods @@ -111,7 +111,7 @@ def extension_create(cmd, client, resource_group_name, cluster_type, cluster_nam extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, version=None, target_namespace=None, release_namespace=None, configuration_settings=None, configuration_protected_settings=None, configuration_settings_file=None, - configuration_protected_settings_file=None, tags=None): + configuration_protected_settings_file=None, tags=None, no_wait=False): provider = ExtensionProvider(cmd) return provider.create(resource_group_name, cluster_type, cluster_name, name, extension_type, scope, auto_upgrade_minor_version, release_train, version, target_namespace, @@ -119,6 +119,6 @@ def extension_create(cmd, client, resource_group_name, cluster_type, cluster_nam configuration_settings_file, configuration_protected_settings_file) -def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False): +def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False): provider = ExtensionProvider(cmd) return provider.delete(resource_group_name, cluster_type, cluster_name, name, force) diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index f3a3a36979d..31b0846e550 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -11,6 +11,7 @@ from azure.cli.core.azclierror import ResourceNotFoundError, MutuallyExclusiveArgumentError from azure.cli.core.commands.client_factory import get_subscription_id +from azure.cli.core.util import sdk_no_wait from ..vendored_sdks.v2021_05_01_preview.models import Identity @@ -80,23 +81,19 @@ def list(self, resource_group_name, cluster_type, cluster_name): cluster_rp = get_cluster_rp(cluster_type) return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - def delete(self, resource_group_name, cluster_type, cluster_name, name, force): + def delete(self, resource_group_name, cluster_type, cluster_name, name, force, no_wait): cluster_rp = get_cluster_rp(cluster_type) if not force: logger.info("Delting the flux configuration from the cluster. This may take a minute...") - return self.client.begin_delete(resource_group_name, - cluster_rp, - cluster_type, - cluster_name, - name, - force_delete=force) + return sdk_no_wait(no_wait, self.client.begin_delete, resource_group_name, + cluster_rp, cluster_type, cluster_name, name, force_delete=force) def create(self, resource_group_name, cluster_type, cluster_name, name, extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, version=None, target_namespace=None, release_namespace=None, configuration_settings=None, configuration_protected_settings=None, configuration_settings_file=None, - configuration_protected_settings_file=None, tags=None): + configuration_protected_settings_file=None, tags=None, no_wait=False): """Create a new Extension Instance. """ @@ -165,12 +162,8 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, cluster_name) logger.info("Starting extension creation on the cluster. This might take a minute...") - return self.client.begin_create(resource_group_name, - cluster_rp, - cluster_type, - cluster_name, - name, - extension_instance) + return sdk_no_wait(no_wait, self.client.begin_create, resource_group_name, cluster_rp, cluster_type, + cluster_name, name, extension_instance) def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name): subscription_id = get_subscription_id(self.cmd.cli_ctx) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index ba25c9ea0f5..9ab8f276b65 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -7,6 +7,7 @@ from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property +from azure.cli.core.util import sdk_no_wait from azure.core.exceptions import HttpResponseError from knack.log import get_logger @@ -83,7 +84,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None, suspend=False, kustomization=None): + known_hosts_file=None, suspend=False, kustomization=None, no_wait=False): # Determine the cluster RP cluster_rp = get_cluster_rp(cluster_type) @@ -123,18 +124,18 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None ) self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name, no_wait) - logger.warning("Creating the fluxConfiguration '%s' in the cluster. This may take a minute...", name) + logger.warning("Creating the flux configuration '%s' in the cluster. This may take a minute...", name) - return self.client.begin_create_or_update(resource_group_name, cluster_rp, - cluster_type, cluster_name, name, flux_configuration) + return sdk_no_wait(no_wait, self.client.begin_create_or_update, resource_group_name, cluster_rp, + cluster_type, cluster_name, name, flux_configuration) def create_source(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None): + known_hosts_file=None, no_wait=False): # Determine the cluster RP cluster_rp = get_cluster_rp(cluster_type) dp_source_kind = "" @@ -143,7 +144,7 @@ def create_source(self, resource_group_name, cluster_type, cluster_name, name, u # Validate the extension install if this is not a deferred command if not self._is_deferred(): self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name, no_wait) if kind == consts.GIT: dp_source_kind = consts.GIT_REPOSITORY @@ -216,13 +217,13 @@ def create_kustomization(self, resource_group_name, cluster_type, cluster_name, cluster_name=cluster_name, setter_arg_name='flux_configuration') return get_property(flux_configuration.kustomizations, name) - def delete(self, resource_group_name, cluster_type, cluster_name, name, force): + def delete(self, resource_group_name, cluster_type, cluster_name, name, force, no_wait): cluster_rp = get_cluster_rp(cluster_type) if not force: logger.info("Delting the flux configuration from the cluster. This may take a minute...") - return self.client.begin_delete(resource_group_name, cluster_rp, cluster_type, - cluster_name, name, force_delete=force) + return sdk_no_wait(no_wait, self.client.begin_delete, resource_group_name, cluster_rp, cluster_type, + cluster_name, name) def _is_deferred(self): if '--defer' in self.cmd.cli_ctx.data.get('safe_params'): @@ -238,7 +239,7 @@ def _validate_source_control_config_not_installed(self, resource_group_name, clu consts.SCC_EXISTS_ON_CLUSTER_ERROR, consts.SCC_EXISTS_ON_CLUSTER_HELP) - def _validate_extension_install(self, resource_group_name, cluster_type, cluster_name): + def _validate_extension_install(self, resource_group_name, cluster_type, cluster_name, no_wait): # Validate if the extension is installed, if not, install it extensions = self.extension_provider.list(resource_group_name, cluster_type, cluster_name) found_flux_extension = False @@ -250,7 +251,7 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster logger.warning("'Micrsoft.Flux' extension not found on the cluster, installing it now." " This may take a minute...") self.extension_provider.create(resource_group_name, cluster_type, cluster_name, - "flux", consts.FLUX_EXTENSION_TYPE).result() + "flux", consts.FLUX_EXTENSION_TYPE, no_wait=no_wait).result() logger.warning("'Microsoft.Flux' extension was successfully installed on the cluster") def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, From b2666c56bbba08260749bb0b621d97d1a8a07226 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 9 Aug 2021 18:01:28 -0700 Subject: [PATCH 42/61] Fix style issues --- src/k8s-config/azext_k8s_config/action.py | 8 +++++++- src/k8s-config/azext_k8s_config/custom.py | 2 +- .../providers/FluxConfigurationProvider.py | 10 +++++----- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/action.py b/src/k8s-config/azext_k8s_config/action.py index 38718d22ae8..9ba3aef1adc 100644 --- a/src/k8s-config/azext_k8s_config/action.py +++ b/src/k8s-config/azext_k8s_config/action.py @@ -39,7 +39,13 @@ def __call__(self, parser, namespace, values, option_string=None): super().__call__( parser, namespace, - KustomizationDefinition(depends_on=dependencies, sync_interval_in_seconds=get_duration(sync_interval), retry_interval_in_seconds=get_duration(retry_interval), timeout_in_seconds=get_duration(timeout), **kwargs), + KustomizationDefinition( + depends_on=dependencies, + sync_interval_in_seconds=get_duration(sync_interval), + retry_interval_in_seconds=get_duration(retry_interval), + timeout_in_seconds=get_duration(timeout), + **kwargs + ), option_string ) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index c151590b00a..d17c0ea093b 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -121,4 +121,4 @@ def extension_create(cmd, client, resource_group_name, cluster_type, cluster_nam def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False): provider = ExtensionProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name, force) + return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 9ab8f276b65..035280346b0 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -126,7 +126,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) self._validate_extension_install(resource_group_name, cluster_type, cluster_name, no_wait) - logger.warning("Creating the flux configuration '%s' in the cluster. This may take a minute...", name) + logger.warning("Creating the flux configuration '%s' in the cluster. This may take a few minutes...", name) return sdk_no_wait(no_wait, self.client.begin_create_or_update, resource_group_name, cluster_rp, cluster_type, cluster_name, name, flux_configuration) @@ -188,7 +188,7 @@ def create_kustomization(self, resource_group_name, cluster_type, cluster_name, # Validate the extension install if this is not a deferred command if not self._is_deferred(): self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name) + self._validate_extension_install(resource_group_name, cluster_type, cluster_name, no_wait=False) flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, @@ -221,7 +221,7 @@ def delete(self, resource_group_name, cluster_type, cluster_name, name, force, n cluster_rp = get_cluster_rp(cluster_type) if not force: - logger.info("Delting the flux configuration from the cluster. This may take a minute...") + logger.info("Delting the flux configuration from the cluster. This may take a few minutes...") return sdk_no_wait(no_wait, self.client.begin_delete, resource_group_name, cluster_rp, cluster_type, cluster_name, name) @@ -248,8 +248,8 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster found_flux_extension = True break if not found_flux_extension: - logger.warning("'Micrsoft.Flux' extension not found on the cluster, installing it now." - " This may take a minute...") + logger.warning("'Microsoft.Flux' extension not found on the cluster, installing it now." + " This may take a few minutes...") self.extension_provider.create(resource_group_name, cluster_type, cluster_name, "flux", consts.FLUX_EXTENSION_TYPE, no_wait=no_wait).result() logger.warning("'Microsoft.Flux' extension was successfully installed on the cluster") From ba86a24736b278bdde0d2ff4bf6643c3914841f8 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 11 Aug 2021 11:48:57 -0700 Subject: [PATCH 43/61] Use base64 encoded httpsUser --- .../providers/FluxConfigurationProvider.py | 19 ++++++++-- .../SourceControlConfigurationProvider.py | 36 ++++++++++++++----- src/k8s-config/azext_k8s_config/utils.py | 25 ------------- src/k8s-config/azext_k8s_config/validators.py | 12 ++++++- 4 files changed, 55 insertions(+), 37 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 035280346b0..6cd19495488 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -12,7 +12,7 @@ from knack.log import get_logger from .._client_factory import k8s_config_fluxconfig_client -from ..utils import get_cluster_rp, get_data_from_key_or_file, get_protected_settings, get_duration +from ..utils import get_cluster_rp, get_data_from_key_or_file, get_duration, to_base64 from ..validators import ( validate_cc_registration, validate_known_hosts, @@ -281,7 +281,7 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time sync_interval_in_seconds=get_duration(sync_interval), repository_ref=repository_ref, ssh_known_hosts=knownhost_data, - https_user=https_user, + https_user=to_base64(https_user), local_auth_ref=local_auth_ref ) @@ -295,3 +295,18 @@ def validate_and_get_repository_ref(branch, tag, semver, commit): semver=semver, commit=commit ) + +def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key): + protected_settings = {} + ssh_private_key_data = get_data_from_key_or_file(ssh_private_key, ssh_private_key_file) + + # Add gitops private key data to protected settings if exists + # Dry-run all key types to determine if the private key is in a valid format + if ssh_private_key_data: + protected_settings[consts.SSH_PRIVATE_KEY_KEY] = ssh_private_key_data + + # Check if both httpsUser and httpsKey exist, then add to protected settings + if https_user and https_key: + protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key) + + return protected_settings \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py index a289d33202d..f0b97e3bc7a 100644 --- a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py @@ -9,7 +9,8 @@ from knack.log import get_logger from .._client_factory import k8s_config_sourcecontrol_client -from ..utils import fix_compliance_state, get_cluster_rp, get_data_from_key_or_file, get_protected_settings +from ..utils import fix_compliance_state, get_cluster_rp, get_data_from_key_or_file, to_base64 +from .. import consts from ..vendored_sdks.v2021_03_01.models import ( HelmOperatorProperties, @@ -81,14 +82,6 @@ def create(self, resource_group_name, cluster_name, name, repository_url, scope, helm_operator_properties.chart_version = helm_operator_chart_version.strip() helm_operator_properties.chart_values = helm_operator_params.strip() - protected_settings = get_protected_settings(ssh_private_key, - ssh_private_key_file, - https_user, - https_key) - knownhost_data = get_data_from_key_or_file(ssh_known_hosts, ssh_known_hosts_file) - if knownhost_data: - validate_known_hosts(knownhost_data) - validate_url_with_params(repository_url, ssh_private_key, ssh_private_key_file, @@ -97,6 +90,14 @@ def create(self, resource_group_name, cluster_name, name, repository_url, scope, https_user, https_key) + protected_settings = get_protected_settings(ssh_private_key, + ssh_private_key_file, + https_user, + https_key) + knownhost_data = get_data_from_key_or_file(ssh_known_hosts, ssh_known_hosts_file) + if knownhost_data: + validate_known_hosts(knownhost_data) + # Validate that the subscription is registered to Microsoft.KubernetesConfiguration validate_cc_registration(self.cmd) @@ -119,3 +120,20 @@ def create(self, resource_group_name, cluster_name, name, repository_url, scope, name, source_control_configuration) return fix_compliance_state(config) + + +def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key): + protected_settings = {} + ssh_private_key_data = get_data_from_key_or_file(ssh_private_key, ssh_private_key_file) + + # Add gitops private key data to protected settings if exists + # Dry-run all key types to determine if the private key is in a valid format + if ssh_private_key_data: + protected_settings[consts.SSH_PRIVATE_KEY_KEY] = ssh_private_key_data + + # Check if both httpsUser and httpsKey exist, then add to protected settings + if https_user and https_key: + protected_settings[consts.HTTPS_USER_KEY] = to_base64(https_user) + protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key) + + return protected_settings \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 6316977da0e..14ce45d0ea6 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -35,31 +35,6 @@ def get_data_from_key_or_file(key, filepath): return data -def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key): - protected_settings = {} - ssh_private_key_data = get_data_from_key_or_file(ssh_private_key, ssh_private_key_file) - - # Add gitops private key data to protected settings if exists - # Dry-run all key types to determine if the private key is in a valid format - if ssh_private_key_data: - protected_settings[consts.SSH_PRIVATE_KEY_KEY] = ssh_private_key_data - - # Check if both httpsUser and httpsKey exist, then add to protected settings - if https_user and https_key: - protected_settings[consts.HTTPS_USER_KEY] = to_base64(https_user) - protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key) - elif https_user: - raise RequiredArgumentMissingError( - consts.HTTPS_USER_WITHOUT_KEY_ERROR, - consts.HTTPS_USER_WITHOUT_KEY_HELP) - elif https_key: - raise RequiredArgumentMissingError( - consts.HTTPS_KEY_WITHOUT_USER_ERROR, - consts.HTTPS_KEY_WITHOUT_USER_HELP) - - return protected_settings - - def read_config_settings_file(file_path): try: with open(file_path, 'r') as f: diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index 51f64341ea9..51be430a890 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -200,11 +200,21 @@ def validate_url_with_params(url: str, ssh_private_key, ssh_private_key_file, if not (https_user and https_key) and scheme == 'https': logger.warning(consts.HTTP_URL_NO_AUTH_WARNING) else: - if https_user and https_key: + if https_user or https_key: raise MutuallyExclusiveArgumentError( consts.HTTPS_AUTH_WITH_SSH_URL_ERROR, consts.HTTPS_AUTH_WITH_SSH_URL_HELP ) + if https_user and https_key: + return + elif https_user: + raise RequiredArgumentMissingError( + consts.HTTPS_USER_WITHOUT_KEY_ERROR, + consts.HTTPS_USER_WITHOUT_KEY_HELP) + elif https_key: + raise RequiredArgumentMissingError( + consts.HTTPS_KEY_WITHOUT_USER_ERROR, + consts.HTTPS_KEY_WITHOUT_USER_HELP) def validate_known_hosts(knownhost_data): From 723507585ae9782934b3649e2d43a8d776f7ed2a Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 13 Aug 2021 11:51:31 -0700 Subject: [PATCH 44/61] Fix formatting error and base64 encoding error --- src/k8s-config/azext_k8s_config/format.py | 4 ++-- .../azext_k8s_config/providers/FluxConfigurationProvider.py | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/format.py b/src/k8s-config/azext_k8s_config/format.py index 134604435e1..35889b20589 100644 --- a/src/k8s-config/azext_k8s_config/format.py +++ b/src/k8s-config/azext_k8s_config/format.py @@ -38,8 +38,8 @@ def __get_extension_table_row(result): ('name', result['name']), ('extensionType', result['extensionType']), ('version', result['version']), - ('installState', result['installState']), - ('lastModifiedTime', result['lastModifiedTime']) + ('provisioningState', result['provisioningState']), + ('lastModifiedAt', result['systemData']['lastModifiedAt']) ]) diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 6cd19495488..369b243c5cf 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -275,13 +275,17 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time repository_ref = validate_and_get_repository_ref(branch, tag, semver, commit) + # Encode the https username to base64 + if https_user: + https_user = to_base64(https_user) + return GitRepositoryDefinition( url=url, timeout_in_seconds=get_duration(timeout), sync_interval_in_seconds=get_duration(sync_interval), repository_ref=repository_ref, ssh_known_hosts=knownhost_data, - https_user=to_base64(https_user), + https_user=https_user, local_auth_ref=local_auth_ref ) From eb67504e0fadde5867654cf7bb05df3d43dd182a Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 13 Aug 2021 15:49:52 -0700 Subject: [PATCH 45/61] Fix style issues --- src/k8s-config/azext_k8s_config/_help.py | 50 ------------------- .../azext_k8s_config/azext_metadata.json | 3 +- src/k8s-config/azext_k8s_config/commands.py | 18 +------ src/k8s-config/azext_k8s_config/custom.py | 31 ------------ src/k8s-config/azext_k8s_config/format.py | 19 ------- .../providers/FluxConfigurationProvider.py | 6 ++- .../SourceControlConfigurationProvider.py | 2 +- src/k8s-config/azext_k8s_config/utils.py | 3 +- src/k8s-config/azext_k8s_config/validators.py | 2 +- 9 files changed, 11 insertions(+), 123 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index ea195ea2dcb..1324989e14e 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -11,56 +11,6 @@ short-summary: Commands to manage resources from Microsoft.KubernetesConfiguration. """ -helps['k8s-config fluxv1'] = """ - type: group - short-summary: Commands to manage Flux V1 Kubernetes configurations. -""" - -helps['k8s-config fluxv1 create'] = """ - type: command - short-summary: Create a Kubernetes configuration. - examples: - - name: Create a Kubernetes configuration - text: |- - az k8s-config fluxv1 create --resource-group MyResourceGroup --cluster-name MyClusterName \\ - --cluster-type connectedClusters --name MyGitConfig --operator-instance-name OperatorInst01 \\ - --operator-namespace OperatorNamespace01 --operator-type flux --operator-params "'--git-readonly'" \\ - --repository-url git://github.com/fluxHowTo/flux-get-started --enable-helm-operator \\ - --helm-operator-chart-version 1.2.0 --scope namespace --helm-operator-params '--set helm.versions=v3' \\ - --ssh-private-key '' --ssh-private-key-file '' --https-user '' --https-key '' \\ - --ssh-known-hosts '' --ssh-known-hosts-file '' -""" - -helps['k8s-config fluxv1 list'] = """ - type: command - short-summary: List Kubernetes configurations. - examples: - - name: List all Kubernetes configurations of a cluster - text: |- - az k8s-config fluxv1 list --resource-group MyResourceGroup --cluster-name MyClusterName \\ - --cluster-type connectedClusters -""" - -helps['k8s-config fluxv1 delete'] = """ - type: command - short-summary: Delete a Kubernetes configuration. - examples: - - name: Delete a Kubernetes configuration - text: |- - az k8s-config fluxv1 delete --resource-group MyResourceGroup --cluster-name MyClusterName \\ - --cluster-type connectedClusters --name MyConfigurationName -""" - -helps['k8s-config fluxv1 show'] = """ - type: command - short-summary: Show details of a Kubernetes configuration. - examples: - - name: Show a Kubernetes configuration - text: |- - az k8s-config fluxv1 show --resource-group MyResourceGroup --cluster-name MyClusterName \\ - --cluster-type connectedClusters --name MyConfigurationName -""" - helps['k8s-config flux'] = """ type: group short-summary: Commands to manage Flux V2 Kubernetes configurations. diff --git a/src/k8s-config/azext_k8s_config/azext_metadata.json b/src/k8s-config/azext_k8s_config/azext_metadata.json index 3695b0d7077..2938e1574ca 100644 --- a/src/k8s-config/azext_k8s_config/azext_metadata.json +++ b/src/k8s-config/azext_k8s_config/azext_metadata.json @@ -1,3 +1,4 @@ { - "azext.minCliCoreVersion": "2.15.0" + "azext.minCliCoreVersion": "2.15.0", + "azext.isExperimental": true } \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index bebdfc32715..3185cb70efd 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -7,16 +7,13 @@ from azure.cli.core.commands import CliCommandType from azext_k8s_config._client_factory import ( k8s_config_fluxconfig_client, - k8s_config_extension_client, - k8s_config_sourcecontrol_client + k8s_config_extension_client ) from .format import ( fluxconfig_list_table_format, fluxconfig_show_table_format, extension_list_table_format, - extension_show_table_format, - sourcecontrol_list_table_format, - sourcecontrol_show_table_format + extension_show_table_format ) @@ -31,11 +28,6 @@ def load_command_table(self, _): client_factory=k8s_config_extension_client ) - k8s_config_sourcecontrol_sdk = CliCommandType( - operations_tmpl='azext_k8s_config.vendored_sdks.operations#SourceControlConfigurationsOperations.{}', - client_factory=k8s_config_sourcecontrol_client - ) - with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_preview=True) as g: g.custom_command('create', 'flux_config_create', supports_no_wait=True) g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) @@ -49,9 +41,3 @@ def load_command_table(self, _): g.custom_command('list', "extension_list", table_transformer=extension_list_table_format) g.custom_command('show', 'extension_show', table_transformer=extension_show_table_format) g.custom_command('delete', 'extension_delete', confirmation=True, supports_no_wait=True) - - with self.command_group('k8s-config fluxv1', k8s_config_sourcecontrol_sdk, client_factory=k8s_config_sourcecontrol_client, deprecate_info=self.deprecate(redirect='k8s-config flux')) as g: - g.custom_command('create', 'sourcecontrol_create') - g.custom_command('list', 'sourcecontrol_list', table_transformer=sourcecontrol_list_table_format) - g.custom_show_command('show', 'sourcecontrol_show', table_transformer=sourcecontrol_show_table_format) - g.custom_command('delete', 'sourcecontrol_delete', confirmation=True) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index d17c0ea093b..9396e186760 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -5,41 +5,10 @@ # pylint: disable=unused-argument -from azext_k8s_config.providers.SourceControlConfigurationProvider import SourceControlConfigurationProvider from .providers.ExtensionProvider import ExtensionProvider from .providers.FluxConfigurationProvider import FluxConfigurationProvider from . import consts -# Source Control Configuration Methods - - -def sourcecontrol_create(cmd, client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, - operator_instance_name=None, operator_namespace='default', - helm_operator_chart_version='1.2.0', operator_type='flux', operator_params='', - ssh_private_key='', ssh_private_key_file='', https_user='', https_key='', - ssh_known_hosts='', ssh_known_hosts_file='', enable_helm_operator=None, - helm_operator_params=''): - provider = SourceControlConfigurationProvider(cmd) - return provider.create(resource_group_name, cluster_name, name, repository_url, scope, cluster_type, - operator_instance_name, operator_namespace, helm_operator_chart_version, operator_type, - operator_params, ssh_private_key, ssh_private_key_file, https_user, https_key, - ssh_known_hosts, ssh_known_hosts_file, enable_helm_operator, helm_operator_params) - - -def sourcecontrol_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): - provider = SourceControlConfigurationProvider(cmd) - return provider.show(resource_group_name, cluster_type, cluster_name, name) - - -def sourcecontrol_list(cmd, client, resource_group_name, cluster_type, cluster_name): - provider = SourceControlConfigurationProvider(cmd) - return provider.list(resource_group_name, cluster_type, cluster_name) - - -def sourcecontrol_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): - provider = SourceControlConfigurationProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name) - # Flux Configuration Methods diff --git a/src/k8s-config/azext_k8s_config/format.py b/src/k8s-config/azext_k8s_config/format.py index 35889b20589..2f6447dd625 100644 --- a/src/k8s-config/azext_k8s_config/format.py +++ b/src/k8s-config/azext_k8s_config/format.py @@ -6,25 +6,6 @@ from collections import OrderedDict -def sourcecontrol_list_table_format(results): - return [__get_sourcecontrolconfig_table_row(result) for result in results] - - -def sourcecontrol_show_table_format(result): - return __get_sourcecontrolconfig_table_row(result) - - -def __get_sourcecontrolconfig_table_row(result): - return OrderedDict([ - ('name', result['name']), - ('repositoryUrl', result['repositoryUrl']), - ('operatorName', result['operatorInstanceName']), - ('operatorNamespace', result['operatorNamespace']), - ('scope', result['operatorScope']), - ('provisioningState', result['provisioningState']) - ]) - - def extension_list_table_format(results): return [__get_extension_table_row(result) for result in results] diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 369b243c5cf..cd27ee318d5 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -7,7 +7,7 @@ from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property -from azure.cli.core.util import sdk_no_wait +from azure.cli.core.util import sdk_no_wait, user_confirmation from azure.core.exceptions import HttpResponseError from knack.log import get_logger @@ -105,6 +105,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None validate_kustomization_list(name, kustomization) else: logger.warning(consts.NO_KUSTOMIZATIONS_WARNING) + user_confirmation("Are you sure you want to proceed without any kustomizations?") # Get the protected settings and validate the private key value protected_settings = get_protected_settings( @@ -300,6 +301,7 @@ def validate_and_get_repository_ref(branch, tag, semver, commit): commit=commit ) + def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key): protected_settings = {} ssh_private_key_data = get_data_from_key_or_file(ssh_private_key, ssh_private_key_file) @@ -313,4 +315,4 @@ def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, ht if https_user and https_key: protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key) - return protected_settings \ No newline at end of file + return protected_settings diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py index f0b97e3bc7a..30f5d9bc3dc 100644 --- a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py @@ -136,4 +136,4 @@ def get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, ht protected_settings[consts.HTTPS_USER_KEY] = to_base64(https_user) protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key) - return protected_settings \ No newline at end of file + return protected_settings diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 14ce45d0ea6..d837db7f873 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -9,8 +9,7 @@ from datetime import timedelta from azure.cli.core.azclierror import ( MutuallyExclusiveArgumentError, - InvalidArgumentValueError, - RequiredArgumentMissingError + InvalidArgumentValueError ) from . import consts diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index 51be430a890..f1f3e7256ec 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -207,7 +207,7 @@ def validate_url_with_params(url: str, ssh_private_key, ssh_private_key_file, ) if https_user and https_key: return - elif https_user: + if https_user: raise RequiredArgumentMissingError( consts.HTTPS_USER_WITHOUT_KEY_ERROR, consts.HTTPS_USER_WITHOUT_KEY_HELP) From fbb349be3aad8ac0efa0f46e177392d79c85d828 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Fri, 13 Aug 2021 16:29:20 -0700 Subject: [PATCH 46/61] Fix force --- src/k8s-config/azext_k8s_config/_help.py | 16 +++++++------- src/k8s-config/azext_k8s_config/_params.py | 22 ++++++++----------- .../azext_k8s_config/azext_metadata.json | 1 + src/k8s-config/azext_k8s_config/commands.py | 2 +- src/k8s-config/azext_k8s_config/consts.py | 7 ++---- .../providers/FluxConfigurationProvider.py | 4 ++-- src/k8s-config/azext_k8s_config/validators.py | 12 +++++----- 7 files changed, 28 insertions(+), 36 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 1324989e14e..06f09df0b21 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -13,7 +13,7 @@ helps['k8s-config flux'] = """ type: group - short-summary: Commands to manage Flux V2 Kubernetes configurations. + short-summary: Commands to manage Flux Configurations. """ helps['k8s-config flux create'] = """ @@ -67,7 +67,7 @@ helps['k8s-config extension'] = """ type: group - short-summary: Commands to manage Flux V2 Kubernetes configurations. + short-summary: Commands to manage Kubernetes Extensions. """ helps['k8s-config extension create'] = """ @@ -83,9 +83,9 @@ helps['k8s-config extension list'] = """ type: command - short-summary: List Kubernetes Flux Configurations. + short-summary: List Kubernetes Extensions. examples: - - name: List all Kubernetes Flux Configurations on a cluster + - name: List all Kubernetes Extensions on a cluster text: |- az k8s-config extension list --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters @@ -93,9 +93,9 @@ helps['k8s-config extension show'] = """ type: command - short-summary: Show a Kubernetes Flux Configuration. + short-summary: Show a Kubernetes Extension. examples: - - name: Show details of a Kubernetes Flux Configuration + - name: Show details of a Kubernetes Extension text: |- az k8s-config extension show --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myextension @@ -103,9 +103,9 @@ helps['k8s-config extension delete'] = """ type: command - short-summary: Delete a Kubernetes Flux Configuration. + short-summary: Delete a Kubernetes Extension. examples: - - name: Delete an existing Kubernetes Flux Configuration + - name: Delete an existing Kubernetes Extension text: |- az k8s-config extension delete --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myextension diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 1cb08a3e781..bf7493c5017 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -52,27 +52,24 @@ def load_arguments(self, _): help='Source kind to reconcile') c.argument('url', options_list=['--url', '-u'], - help='URL of the source to reconcile') + help='URL of the git repo source to reconcile') c.argument('timeout', help='Maximum time to reconcile the source before timing out') c.argument('sync_interval', options_list=['--interval', '--sync-interval'], help='Time between reconciliations of the source on the cluster') c.argument('branch', - arg_group="Repo Ref", - help='Branch to reconcile with the git source') + arg_group="Git Repo Ref", + help='Branch within the git source to reconcile with the cluster') c.argument('tag', - arg_group="Repo Ref", - help='Tag to reconcile with the git source') + arg_group="Git Repo Ref", + help='Tag within the git source to reconcile with the cluster') c.argument('semver', - arg_group="Repo Ref", - help='Semver range to reconcile with the git source') + arg_group="Git Repo Ref", + help='Semver range within the git source to reconcile with the cluster') c.argument('commit', - arg_group="Repo Ref", - help='Specific commit to reconcile with the git source') - c.argument('branch_commit', - arg_group="Repo Ref", - help="Specific commit and branch to reconcile with the git source") + arg_group="Git Repo Ref", + help='Commit within the git source to reconcile with the cluster') c.argument('ssh_private_key', arg_group="Auth", help='Base64-encoded private ssh key for private repository sync') @@ -98,7 +95,6 @@ def load_arguments(self, _): c.argument('suspend', help='Suspend the reconciliation of the source and kustomizations associated with this configuration') c.argument('kustomization', - options_list=['--kustomization', '-k'], action=KustomizationAddAction, help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", nargs='+') diff --git a/src/k8s-config/azext_k8s_config/azext_metadata.json b/src/k8s-config/azext_k8s_config/azext_metadata.json index 2938e1574ca..9a4dbb92de4 100644 --- a/src/k8s-config/azext_k8s_config/azext_metadata.json +++ b/src/k8s-config/azext_k8s_config/azext_metadata.json @@ -1,4 +1,5 @@ { "azext.minCliCoreVersion": "2.15.0", + "azext.isPreview": true, "azext.isExperimental": true } \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index 3185cb70efd..a69f9067f70 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -28,7 +28,7 @@ def load_command_table(self, _): client_factory=k8s_config_extension_client ) - with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_preview=True) as g: + with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_experimental=True) as g: g.custom_command('create', 'flux_config_create', supports_no_wait=True) g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) g.custom_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 36d44dbdf9e..8bf411a9d82 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -70,11 +70,8 @@ SSH_PRIVATE_KEY_ERROR = "Error! --ssh-private-key provided in invalid format" SSH_PRIVATE_KEY_HELP = "Verify the key provided is a valid PEM-formatted key of type RSA, ECC, DSA, or Ed25519" -HTTPS_USER_WITHOUT_KEY_ERROR = "Error! --https-user used without --https-key" -HTTPS_USER_WITHOUT_KEY_HELP = "Try providing both --https-user and --https-key together" - -HTTPS_KEY_WITHOUT_USER_ERROR = "Error! --http-key used without --http-user" -HTTPS_KEY_WITHOUT_USER_HELP = "Try providing both --https-user and --https-key together" +HTTPS_USER_KEY_MATCH_ERROR = "Error! --https-user and --https-key cannot be used separately" +HTTPS_USER_KEY_MATCH_HELP = "Try providing both --https-user and --https-key together" KEY_FILE_READ_ERROR = "Error! Unable to read key file specified with: {0}" KEY_FILE_READ_HELP = "Verify that the filepath specified exists and contains valid utf-8 data" diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index cd27ee318d5..0400222c66c 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -222,9 +222,9 @@ def delete(self, resource_group_name, cluster_type, cluster_name, name, force, n cluster_rp = get_cluster_rp(cluster_type) if not force: - logger.info("Delting the flux configuration from the cluster. This may take a few minutes...") + logger.info("Deleting the flux configuration from the cluster. This may take a few minutes...") return sdk_no_wait(no_wait, self.client.begin_delete, resource_group_name, cluster_rp, cluster_type, - cluster_name, name) + cluster_name, name, force_delete=force) def _is_deferred(self): if '--defer' in self.cmd.cli_ctx.data.get('safe_params'): diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index f1f3e7256ec..a0810c11e3f 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -205,16 +205,14 @@ def validate_url_with_params(url: str, ssh_private_key, ssh_private_key_file, consts.HTTPS_AUTH_WITH_SSH_URL_ERROR, consts.HTTPS_AUTH_WITH_SSH_URL_HELP ) + if https_user and https_key: return - if https_user: - raise RequiredArgumentMissingError( - consts.HTTPS_USER_WITHOUT_KEY_ERROR, - consts.HTTPS_USER_WITHOUT_KEY_HELP) - elif https_key: + # If we just provide one or the other raise an error + if https_user or https_key: raise RequiredArgumentMissingError( - consts.HTTPS_KEY_WITHOUT_USER_ERROR, - consts.HTTPS_KEY_WITHOUT_USER_HELP) + consts.HTTPS_USER_KEY_MATCH_ERROR, + consts.HTTPS_USER_KEY_MATCH_HELP) def validate_known_hosts(knownhost_data): From 2d736802688b1d744ce37289397060d459c184bc Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 18 Aug 2021 15:19:16 -0700 Subject: [PATCH 47/61] Updated help text --- src/k8s-config/azext_k8s_config/_help.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 06f09df0b21..69705dbe8ae 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -24,15 +24,8 @@ text: |- az k8s-config flux create --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ - --kind git --url https://github.com/Azure/arc-k8s-demo --branch main --kustomization \\ - name=my-kustomization path="./apps" - - name: Create a Kubernetes Flux Configuration with Multiple Kustomizations - text: |- - az k8s-config flux create --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ - --kind git --url https://github.com/Azure/arc-k8s-demo --https-user my-username \\ - --https-key my-password --branch main --kustomization name=my-crds path="./crds" \\ - --kustomization name=my-apps path="./apps" depends_on=my-crds timeout=PT5M + --kind git --url https://github.com/Azure/arc-k8s-demo --branch master --kustomization \\ + name=my-kustomization """ helps['k8s-config flux list'] = """ From dccb42ae42c408139cd7d6d0bbd71b93bf06c00e Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 19 Aug 2021 10:12:25 -0700 Subject: [PATCH 48/61] Style fixes --- src/k8s-config/azext_k8s_config/_help.py | 5 +++-- src/k8s-config/azext_k8s_config/_params.py | 2 ++ src/k8s-config/azext_k8s_config/commands.py | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py index 69705dbe8ae..31466d7c818 100644 --- a/src/k8s-config/azext_k8s_config/_help.py +++ b/src/k8s-config/azext_k8s_config/_help.py @@ -69,8 +69,9 @@ examples: - name: Create a Kubernetes Extension text: |- - az k8s-config extension create --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters --name myextension --extension-type microsoft.openservicemesh \\ + az k8s-config extension create --resource-group my-resource-group \\ + --cluster-name mycluster --cluster-type connectedClusters \\ + --name myextension --extension-type microsoft.openservicemesh \\ --scope cluster --release-train stable """ diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index bf7493c5017..3959cd30923 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -110,6 +110,8 @@ def load_arguments(self, _): validator=validate_extension_name) with self.argument_context('k8s-config extension create') as c: + c.argument('extension_type', + help='Name of the extension type.') c.argument('scope', arg_type=get_enum_type(['cluster', 'namespace']), help='Specify the extension scope.') diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py index a69f9067f70..1738bd9cd6f 100644 --- a/src/k8s-config/azext_k8s_config/commands.py +++ b/src/k8s-config/azext_k8s_config/commands.py @@ -31,7 +31,7 @@ def load_command_table(self, _): with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_experimental=True) as g: g.custom_command('create', 'flux_config_create', supports_no_wait=True) g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) - g.custom_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) + g.custom_show_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) g.custom_command('delete', 'flux_config_delete', confirmation=True, supports_no_wait=True) # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) @@ -39,5 +39,5 @@ def load_command_table(self, _): with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: g.custom_command('create', 'extension_create', supports_no_wait=True) g.custom_command('list', "extension_list", table_transformer=extension_list_table_format) - g.custom_command('show', 'extension_show', table_transformer=extension_show_table_format) + g.custom_show_command('show', 'extension_show', table_transformer=extension_show_table_format) g.custom_command('delete', 'extension_delete', confirmation=True, supports_no_wait=True) From af9e3f06dc2a6221c658000b429d6916157f66be Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 23 Aug 2021 14:56:21 -0700 Subject: [PATCH 49/61] Increase namespace maximum len --- src/k8s-config/azext_k8s_config/validators.py | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-config/azext_k8s_config/validators.py index a0810c11e3f..8330b5d9ad7 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-config/azext_k8s_config/validators.py @@ -25,22 +25,9 @@ logger = get_logger(__name__) -# Parameter-Level Validation -def validate_configuration_type(configuration_type): - if configuration_type.lower() != 'sourcecontrolconfiguration': - raise InvalidArgumentValueError( - 'Invalid configuration-type', - 'Try specifying the valid value "sourceControlConfiguration"') - - def validate_namespace(namespace): if namespace.namespace: - __validate_k8s_name(namespace.namespace, "--namespace", 23) - - -def validate_operator_instance_name(namespace): - if namespace.operator_instance_name: - __validate_k8s_name(namespace.operator_instance_name, "--operator-instance-name", 23) + __validate_k8s_name(namespace.namespace, "--namespace", 63) def validate_configuration_name(namespace): From 7142aecddd0951b80f5b49bd61fce3f58bc5829f Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 24 Aug 2021 16:58:25 -0700 Subject: [PATCH 50/61] Add managed cluster support to k8s-config --- src/k8s-config/azext_k8s_config/_params.py | 116 +++++++++--------- src/k8s-config/azext_k8s_config/consts.py | 4 + .../providers/ExtensionProvider.py | 8 +- src/k8s-config/azext_k8s_config/utils.py | 11 +- 4 files changed, 77 insertions(+), 62 deletions(-) diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py index 3959cd30923..7b44aea50af 100644 --- a/src/k8s-config/azext_k8s_config/_params.py +++ b/src/k8s-config/azext_k8s_config/_params.py @@ -11,7 +11,7 @@ get_three_state_flag, tags_type ) -from .validators import validate_configuration_name, validate_extension_name, validate_fluxconfig_name, validate_namespace, validate_operator_instance_name, validate_operator_namespace +from .validators import validate_extension_name, validate_fluxconfig_name, validate_namespace from .action import ( KustomizationAddAction, AddConfigurationProtectedSettings, @@ -157,64 +157,64 @@ def load_arguments(self, _): c.argument('force', help='Specify whether to force delete the extension from the cluster.') - with self.argument_context('k8s-config fluxv1') as c: - c.argument('name', - options_list=['--name', '-n'], - help='Name of the configuration', - validator=validate_configuration_name) + # with self.argument_context('k8s-config fluxv1') as c: + # c.argument('name', + # options_list=['--name', '-n'], + # help='Name of the configuration', + # validator=validate_configuration_name) - with self.argument_context('k8s-config fluxv1 create') as c: - c.argument('repository_url', - options_list=['--repository-url', '-u'], - help='Url of the source control repository') - c.argument('scope', - arg_type=get_enum_type(['namespace', 'cluster']), - help='''Specify scope of the operator to be 'namespace' or 'cluster' ''') - c.argument('enable_helm_operator', - arg_group="Helm Operator", - arg_type=get_three_state_flag(), - options_list=['--enable-helm-operator', '--enable-hop'], - help='Enable support for Helm chart deployments') - c.argument('helm_operator_params', - arg_group="Helm Operator", - options_list=['--helm-operator-params', '--hop-params'], - help='Chart values for the Helm Operator (if enabled)') - c.argument('helm_operator_chart_version', - arg_group="Helm Operator", - options_list=['--helm-operator-chart-version', '--hop-chart-version'], - help='Chart version of the Helm Operator (if enabled)') - c.argument('operator_params', - arg_group="Operator", - help='Parameters for the Operator') - c.argument('operator_instance_name', - arg_group="Operator", - help='Instance name of the Operator', - validator=validate_operator_instance_name) - c.argument('operator_namespace', - arg_group="Operator", - help='Namespace in which to install the Operator', - validator=validate_operator_namespace) - c.argument('operator_type', - arg_group="Operator", - help='''Type of the operator. Valid value is 'flux' ''') - c.argument('ssh_private_key', - arg_group="Auth", - help='Specify Base64-encoded private ssh key for private repository sync') - c.argument('ssh_private_key_file', - arg_group="Auth", - help='Specify filepath to private ssh key for private repository sync') - c.argument('https_user', - arg_group="Auth", - help='Specify HTTPS username for private repository sync') - c.argument('https_key', - arg_group="Auth", - help='Specify HTTPS token/password for private repository sync') - c.argument('ssh_known_hosts', - arg_group="Auth", - help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') - c.argument('ssh_known_hosts_file', - arg_group="Auth", - help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') + # with self.argument_context('k8s-config fluxv1 create') as c: + # c.argument('repository_url', + # options_list=['--repository-url', '-u'], + # help='Url of the source control repository') + # c.argument('scope', + # arg_type=get_enum_type(['namespace', 'cluster']), + # help='''Specify scope of the operator to be 'namespace' or 'cluster' ''') + # c.argument('enable_helm_operator', + # arg_group="Helm Operator", + # arg_type=get_three_state_flag(), + # options_list=['--enable-helm-operator', '--enable-hop'], + # help='Enable support for Helm chart deployments') + # c.argument('helm_operator_params', + # arg_group="Helm Operator", + # options_list=['--helm-operator-params', '--hop-params'], + # help='Chart values for the Helm Operator (if enabled)') + # c.argument('helm_operator_chart_version', + # arg_group="Helm Operator", + # options_list=['--helm-operator-chart-version', '--hop-chart-version'], + # help='Chart version of the Helm Operator (if enabled)') + # c.argument('operator_params', + # arg_group="Operator", + # help='Parameters for the Operator') + # c.argument('operator_instance_name', + # arg_group="Operator", + # help='Instance name of the Operator', + # validator=validate_operator_instance_name) + # c.argument('operator_namespace', + # arg_group="Operator", + # help='Namespace in which to install the Operator', + # validator=validate_operator_namespace) + # c.argument('operator_type', + # arg_group="Operator", + # help='''Type of the operator. Valid value is 'flux' ''') + # c.argument('ssh_private_key', + # arg_group="Auth", + # help='Specify Base64-encoded private ssh key for private repository sync') + # c.argument('ssh_private_key_file', + # arg_group="Auth", + # help='Specify filepath to private ssh key for private repository sync') + # c.argument('https_user', + # arg_group="Auth", + # help='Specify HTTPS username for private repository sync') + # c.argument('https_key', + # arg_group="Auth", + # help='Specify HTTPS token/password for private repository sync') + # c.argument('ssh_known_hosts', + # arg_group="Auth", + # help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') + # c.argument('ssh_known_hosts_file', + # arg_group="Auth", + # help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') with self.argument_context('k8s-config flux source') as c: c.argument('scope', diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 8bf411a9d82..44b78dc37b8 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -117,8 +117,12 @@ CONNECTED_CLUSTERS = "connectedclusters" MANAGED_CLUSTERS = "managedclusters" +APPLIANCES = "appliances" MANAGED_RP_NAMESPACE = "Microsoft.ContainerService" CONNECTED_RP_NAMESPACE = "Microsoft.Kubernetes" +APPLIANCE_RP_NAMESPACE = "Microsoft.ResourceConnector" KUBERNETES_MAX_NAME_SIZE = 63 + +DF_RM_ENDPOINT = 'https://api-dogfood.resources.windows-int.net/' diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py index 31b0846e550..2d4d2537fc4 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py @@ -21,7 +21,7 @@ from ..partner_extensions.DefaultExtension import DefaultExtension from ..partner_extensions.DefaultExtensionWithIdentity import DefaultExtensionWithIdentity -from ..utils import get_cluster_rp, get_parent_api_version, read_config_settings_file +from ..utils import get_cluster_rp, get_parent_api_version, read_config_settings_file, is_dogfood_cluster from ..validators import ( validate_scope_and_namespace, validate_version_and_auto_upgrade, @@ -31,6 +31,8 @@ from .._client_factory import cf_resources from .._client_factory import k8s_config_extension_client +from .. import consts + logger = get_logger(__name__) @@ -154,7 +156,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, validate_scope_after_customization(extension_instance.scope) # Create identity, if required - if create_identity: + if create_identity and not is_dogfood_cluster(self.cmd): extension_instance = self.__add_identity(extension_instance, resource_group_name, cluster_rp, @@ -175,6 +177,8 @@ def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cl cluster_type, cluster_name) + if cluster_rp == consts.MANAGED_RP_NAMESPACE: + return extension_instance parent_api_version = get_parent_api_version(cluster_rp) try: resource = resources.get_by_id(cluster_resource_id, parent_api_version) diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index d837db7f873..14bf691391b 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -17,8 +17,11 @@ def get_cluster_rp(cluster_type): if cluster_type.lower() == consts.CONNECTED_CLUSTERS: return consts.CONNECTED_RP_NAMESPACE - # Since cluster_type is an enum of only two values, if not connectedClusters, it will be managedClusters. - return consts.MANAGED_RP_NAMESPACE + if cluster_type.lower() == consts.APPLIANCES: + return consts.APPLIANCE_RP_NAMESPACE + if cluster_type.lower() == '' or cluster_type.lower() == 'managedclusters': + return consts.MANAGED_RP_NAMESPACE + raise InvalidArgumentValueError("Error! Cluster type '{}' is not supported".format(cluster_type)) def get_data_from_key_or_file(key, filepath): @@ -108,3 +111,7 @@ def get_parent_api_version(cluster_rp): return '2017-07-01' raise InvalidArgumentValueError("Error! Cluster RP '{}' is not supported" " for extension identity".format(cluster_rp)) + + +def is_dogfood_cluster(cmd): + return cmd.cli_ctx.cloud.endpoints.resource_manager == consts.DF_RM_ENDPOINT From 86b681a6f14c77c4db27e752fa59521b13b3be03 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 25 Aug 2021 13:17:38 -0700 Subject: [PATCH 51/61] Custom confirmation when prune is enabled --- src/k8s-config/azext_k8s_config/confirm.py | 12 ++++++++++ src/k8s-config/azext_k8s_config/consts.py | 3 +++ src/k8s-config/azext_k8s_config/custom.py | 4 ++-- .../providers/FluxConfigurationProvider.py | 24 ++++++++++++++++--- src/k8s-config/azext_k8s_config/utils.py | 7 ++++++ testing/Test.ps1 | 2 +- 6 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 src/k8s-config/azext_k8s_config/confirm.py diff --git a/src/k8s-config/azext_k8s_config/confirm.py b/src/k8s-config/azext_k8s_config/confirm.py new file mode 100644 index 00000000000..2f8d3a6bdd6 --- /dev/null +++ b/src/k8s-config/azext_k8s_config/confirm.py @@ -0,0 +1,12 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core.util import user_confirmation + + +def user_confirmation_factory(cmd, yes, message="Are you sure you want to perform this operation?"): + if cmd.cli_ctx.config.getboolean('core', 'disable_confirm_prompt', fallback=False): + return + user_confirmation(message, yes=yes) diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-config/azext_k8s_config/consts.py index 44b78dc37b8..cbd6259afad 100644 --- a/src/k8s-config/azext_k8s_config/consts.py +++ b/src/k8s-config/azext_k8s_config/consts.py @@ -126,3 +126,6 @@ KUBERNETES_MAX_NAME_SIZE = 63 DF_RM_ENDPOINT = 'https://api-dogfood.resources.windows-int.net/' + +FLUX_EXTENSION_RELEASETRAIN = "FLUX_EXTENSION_RELEASETRAIN" +FLUX_EXTENSION_VERSION = "FLUX_EXTENSION_VERSION" diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py index 9396e186760..8686638a649 100644 --- a/src/k8s-config/azext_k8s_config/custom.py +++ b/src/k8s-config/azext_k8s_config/custom.py @@ -59,9 +59,9 @@ def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_t validation, force) -def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False): +def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False, yes=False): provider = FluxConfigurationProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait) + return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait, yes) # Extension Methods diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py index 0400222c66c..0e1741611dd 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py @@ -5,6 +5,10 @@ # pylint: disable=unused-argument +import os +from re import L +from azext_k8s_config.confirm import user_confirmation_factory + from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property from azure.cli.core.util import sdk_no_wait, user_confirmation @@ -12,7 +16,7 @@ from knack.log import get_logger from .._client_factory import k8s_config_fluxconfig_client -from ..utils import get_cluster_rp, get_data_from_key_or_file, get_duration, to_base64 +from ..utils import get_cluster_rp, get_data_from_key_or_file, get_duration, has_prune_enabled, to_base64 from ..validators import ( validate_cc_registration, validate_known_hosts, @@ -218,9 +222,20 @@ def create_kustomization(self, resource_group_name, cluster_type, cluster_name, cluster_name=cluster_name, setter_arg_name='flux_configuration') return get_property(flux_configuration.kustomizations, name) - def delete(self, resource_group_name, cluster_type, cluster_name, name, force, no_wait): + def delete(self, resource_group_name, cluster_type, cluster_name, name, force, no_wait, yes): cluster_rp = get_cluster_rp(cluster_type) + config = None + try: + config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name) + except HttpResponseError: + logger.warning("No flux configuration with name '%s' found on cluster '%s', so nothing to delete", name, cluster_name) + return None + + if has_prune_enabled(config): + logger.warning("Prune is enabled on one or more of your kustomizations. Deleting a Flux configuration with prune enabled will also delete the Kubernetes objects deployed by the kustomization(s).") + user_confirmation_factory(self.cmd, yes, "Do you want to continue?") + if not force: logger.info("Deleting the flux configuration from the cluster. This may take a few minutes...") return sdk_no_wait(no_wait, self.client.begin_delete, resource_group_name, cluster_rp, cluster_type, @@ -252,7 +267,10 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster logger.warning("'Microsoft.Flux' extension not found on the cluster, installing it now." " This may take a few minutes...") self.extension_provider.create(resource_group_name, cluster_type, cluster_name, - "flux", consts.FLUX_EXTENSION_TYPE, no_wait=no_wait).result() + "flux", consts.FLUX_EXTENSION_TYPE, + release_train=os.getenv(consts.FLUX_EXTENSION_RELEASETRAIN), + version=os.getenv(consts.FLUX_EXTENSION_VERSION), + no_wait=no_wait).result() logger.warning("'Microsoft.Flux' extension was successfully installed on the cluster") def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-config/azext_k8s_config/utils.py index 14bf691391b..2edc4d9ae7d 100644 --- a/src/k8s-config/azext_k8s_config/utils.py +++ b/src/k8s-config/azext_k8s_config/utils.py @@ -115,3 +115,10 @@ def get_parent_api_version(cluster_rp): def is_dogfood_cluster(cmd): return cmd.cli_ctx.cloud.endpoints.resource_manager == consts.DF_RM_ENDPOINT + + +def has_prune_enabled(config): + for kustomization in config.kustomizations: + if kustomization.prune: + return True + return False diff --git a/testing/Test.ps1 b/testing/Test.ps1 index c9fa58c1856..e862344a29f 100644 --- a/testing/Test.ps1 +++ b/testing/Test.ps1 @@ -73,7 +73,7 @@ if ($Type -eq 'k8s-extension') { az extension add --source ./bin/k8s_config-$k8sConfigVersion-py3-none-any.whl } $Env:K8sExtensionName = "k8s-config" - $testFilePath = "$PSScriptRoot/test" + $testFilePath = "$PSScriptRoot/test/extensions" $excludePath = "$PSScriptRoot/test/extensions/private" } From 842532e7072c7ddc4aa8042865e2fce8c29ecf40 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 7 Sep 2021 12:55:24 -0700 Subject: [PATCH 52/61] Add flux commands to existing k8s-configuration --- src/k8s-config/HISTORY.rst | 9 - src/k8s-config/README.rst | 5 - src/k8s-config/azext_k8s_config/__init__.py | 32 -- .../azext_k8s_config/_client_factory.py | 45 -- src/k8s-config/azext_k8s_config/_help.py | 106 ---- src/k8s-config/azext_k8s_config/_params.py | 295 ---------- .../azext_k8s_config/azext_metadata.json | 5 - src/k8s-config/azext_k8s_config/commands.py | 43 -- src/k8s-config/azext_k8s_config/custom.py | 93 ---- .../azext_k8s_config/tests/__init__.py | 5 - .../azext_k8s_config/tests/latest/__init__.py | 5 - .../test_kubernetesconfiguration_scenario.py | 138 ----- .../tests/latest/test_validators.py | 176 ------ .../vendored_sdks/__init__.py | 16 - .../vendored_sdks/_configuration.py | 71 --- .../_source_control_configuration_client.py | 280 ---------- src/k8s-config/setup.cfg | 0 src/k8s-config/setup.py | 58 -- src/k8s-configuration/HISTORY.rst | 4 + src/k8s-configuration/README.rst | 10 +- .../azext_k8s_configuration/__init__.py | 14 +- .../_client_factory.py | 35 +- .../azext_k8s_configuration/_consts.py | 7 - .../azext_k8s_configuration/_format.py | 25 - .../azext_k8s_configuration/_help.py | 99 +++- .../azext_k8s_configuration/_params.py | 194 ++++++- .../azext_k8s_configuration/_utils.py | 61 -- .../azext_k8s_configuration/_validators.py | 143 ----- .../azext_k8s_configuration}/action.py | 0 .../azext_k8s_configuration/commands.py | 40 +- .../azext_k8s_configuration}/confirm.py | 0 .../azext_k8s_configuration}/consts.py | 0 .../azext_k8s_configuration/custom.py | 332 ++++------- .../azext_k8s_configuration}/format.py | 19 +- .../partner_extensions/AzureDefender.py | 0 .../partner_extensions/AzureMLKubernetes.py | 0 .../partner_extensions/Cassandra.py | 0 .../partner_extensions/ContainerInsights.py | 0 .../partner_extensions/DefaultExtension.py | 0 .../DefaultExtensionWithIdentity.py | 0 .../partner_extensions/OpenServiceMesh.py | 0 .../PartnerExtensionModel.py | 0 .../partner_extensions/__init__.py | 0 .../providers/ExtensionProvider.py | 4 +- .../providers/FluxConfigurationProvider.py | 6 +- .../SourceControlConfigurationProvider.py | 6 +- .../providers/__init__.py | 0 .../data/azure_ml/cert_and_key_encoded.txt | 0 .../tests/latest/data/azure_ml/test_cert.pem | 0 .../tests/latest/data/azure_ml/test_key.pem | 0 .../test_k8s_configuration_success.yaml | 441 --------------- .../tests/latest/test_azureml_extension.py | 0 .../tests/latest/test_k8s-config_scenario.py | 0 .../latest/test_k8s_extension_scenario.py | 0 .../tests/latest/test_open_service_mesh.py | 0 .../azext_k8s_configuration}/utils.py | 0 .../azext_k8s_configuration}/validators.py | 5 + .../vendored_sdks/__init__.py | 19 +- .../vendored_sdks/_configuration.py | 72 ++- .../_source_control_configuration_client.py | 285 +++++++++- .../vendored_sdks/_version.py | 0 .../vendored_sdks/aio/__init__.py | 0 .../vendored_sdks/aio/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../vendored_sdks/aio/operations/__init__.py | 0 .../aio/operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../vendored_sdks/models.py | 0 .../vendored_sdks/models/__init__.py | 73 --- .../vendored_sdks/models/_models.py | 527 ------------------ .../vendored_sdks/models/_models_py3.py | 527 ------------------ .../vendored_sdks/models/_paged_models.py | 40 -- ...urce_control_configuration_client_enums.py | 56 -- .../vendored_sdks/operations/__init__.py | 18 - .../vendored_sdks/operations/_operations.py | 101 ---- ...ource_control_configurations_operations.py | 386 ------------- .../v2020_07_01_preview/__init__.py | 0 .../v2020_07_01_preview/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../v2020_07_01_preview/_version.py | 0 .../v2020_07_01_preview/aio/__init__.py | 0 .../v2020_07_01_preview/aio/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../aio/operations/__init__.py | 0 .../aio/operations/_extensions_operations.py | 0 .../aio/operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../v2020_07_01_preview/models/__init__.py | 0 .../v2020_07_01_preview/models/_models.py | 0 .../v2020_07_01_preview/models/_models_py3.py | 0 ...urce_control_configuration_client_enums.py | 0 .../operations/__init__.py | 0 .../operations/_extensions_operations.py | 0 .../operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../v2020_10_01_preview/__init__.py | 0 .../v2020_10_01_preview/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../v2020_10_01_preview/_version.py | 0 .../v2020_10_01_preview/aio/__init__.py | 0 .../v2020_10_01_preview/aio/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../aio/operations/__init__.py | 0 .../aio/operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../v2020_10_01_preview/models/__init__.py | 0 .../v2020_10_01_preview/models/_models.py | 0 .../v2020_10_01_preview/models/_models_py3.py | 0 ...urce_control_configuration_client_enums.py | 0 .../operations/__init__.py | 0 .../operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../vendored_sdks/v2021_03_01/__init__.py | 0 .../v2021_03_01/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../vendored_sdks/v2021_03_01/_version.py | 0 .../vendored_sdks/v2021_03_01/aio/__init__.py | 0 .../v2021_03_01/aio/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../v2021_03_01/aio/operations/__init__.py | 0 .../v2021_03_01/aio/operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../v2021_03_01/models/__init__.py | 0 .../v2021_03_01/models/_models.py | 0 .../v2021_03_01/models/_models_py3.py | 0 ...urce_control_configuration_client_enums.py | 0 .../v2021_03_01/operations/__init__.py | 0 .../v2021_03_01/operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../v2021_05_01_preview/__init__.py | 0 .../v2021_05_01_preview/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../v2021_05_01_preview/_version.py | 0 .../v2021_05_01_preview/aio/__init__.py | 0 .../v2021_05_01_preview/aio/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../aio/operations/__init__.py | 0 .../_cluster_extension_type_operations.py | 0 .../_cluster_extension_types_operations.py | 0 .../_extension_type_versions_operations.py | 0 .../aio/operations/_extensions_operations.py | 0 .../_location_extension_types_operations.py | 0 .../_operation_status_operations.py | 0 .../aio/operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../v2021_05_01_preview/models/__init__.py | 0 .../v2021_05_01_preview/models/_models.py | 0 .../v2021_05_01_preview/models/_models_py3.py | 0 ...urce_control_configuration_client_enums.py | 0 .../operations/__init__.py | 0 .../_cluster_extension_type_operations.py | 0 .../_cluster_extension_types_operations.py | 0 .../_extension_type_versions_operations.py | 0 .../operations/_extensions_operations.py | 0 .../_location_extension_types_operations.py | 0 .../_operation_status_operations.py | 0 .../operations/_operations.py | 0 ...ource_control_configurations_operations.py | 0 .../v2021_06_01_preview/__init__.py | 0 .../v2021_06_01_preview/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../v2021_06_01_preview/_version.py | 0 .../v2021_06_01_preview/aio/__init__.py | 0 .../v2021_06_01_preview/aio/_configuration.py | 0 .../_source_control_configuration_client.py | 0 .../aio/operations/__init__.py | 0 ...flux_config_operation_status_operations.py | 0 .../_flux_configurations_operations.py | 0 .../_operation_status_operations.py | 0 .../aio/operations/_operations.py | 0 .../v2021_06_01_preview/models/__init__.py | 0 .../v2021_06_01_preview/models/_models.py | 0 .../v2021_06_01_preview/models/_models_py3.py | 0 ...urce_control_configuration_client_enums.py | 0 .../operations/__init__.py | 0 ...flux_config_operation_status_operations.py | 0 .../_flux_configurations_operations.py | 0 .../_operation_status_operations.py | 0 .../operations/_operations.py | 0 .../vendored_sdks/version.py | 13 - src/k8s-configuration/setup.py | 7 +- 181 files changed, 790 insertions(+), 4161 deletions(-) delete mode 100644 src/k8s-config/HISTORY.rst delete mode 100644 src/k8s-config/README.rst delete mode 100644 src/k8s-config/azext_k8s_config/__init__.py delete mode 100644 src/k8s-config/azext_k8s_config/_client_factory.py delete mode 100644 src/k8s-config/azext_k8s_config/_help.py delete mode 100644 src/k8s-config/azext_k8s_config/_params.py delete mode 100644 src/k8s-config/azext_k8s_config/azext_metadata.json delete mode 100644 src/k8s-config/azext_k8s_config/commands.py delete mode 100644 src/k8s-config/azext_k8s_config/custom.py delete mode 100644 src/k8s-config/azext_k8s_config/tests/__init__.py delete mode 100644 src/k8s-config/azext_k8s_config/tests/latest/__init__.py delete mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py delete mode 100644 src/k8s-config/azext_k8s_config/tests/latest/test_validators.py delete mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py delete mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py delete mode 100644 src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py delete mode 100644 src/k8s-config/setup.cfg delete mode 100644 src/k8s-config/setup.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/_consts.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/_format.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/_utils.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/_validators.py rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/action.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/confirm.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/consts.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/format.py (64%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/AzureDefender.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/AzureMLKubernetes.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/Cassandra.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/ContainerInsights.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/DefaultExtension.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/DefaultExtensionWithIdentity.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/OpenServiceMesh.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/PartnerExtensionModel.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/partner_extensions/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/providers/ExtensionProvider.py (98%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/providers/FluxConfigurationProvider.py (98%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/providers/SourceControlConfigurationProvider.py (96%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/providers/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/tests/latest/data/azure_ml/cert_and_key_encoded.txt (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/tests/latest/data/azure_ml/test_cert.pem (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/tests/latest/data/azure_ml/test_key.pem (100%) delete mode 100644 src/k8s-configuration/azext_k8s_configuration/tests/latest/recordings/test_k8s_configuration_success.yaml rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/tests/latest/test_azureml_extension.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/tests/latest/test_k8s-config_scenario.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/tests/latest/test_k8s_extension_scenario.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/tests/latest/test_open_service_mesh.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/utils.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/validators.py (98%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/_version.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/aio/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/aio/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/aio/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/aio/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/aio/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/aio/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/models.py (100%) delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models_py3.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_paged_models.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_source_control_configuration_client_enums.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_operations.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_source_control_configurations_operations.py rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/_version.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/aio/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/aio/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/models/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/models/_models.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/models/_models_py3.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/_version.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/aio/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/aio/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/models/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/models/_models.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/models/_models_py3.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/_version.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/aio/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/aio/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/aio/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/aio/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/models/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/models/_models.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/models/_models_py3.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/_version.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/models/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/models/_models.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/models/_models_py3.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/_version.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/_configuration.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/models/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/models/_models.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/models/_models_py3.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/operations/__init__.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py (100%) rename src/{k8s-config/azext_k8s_config => k8s-configuration/azext_k8s_configuration}/vendored_sdks/v2021_06_01_preview/operations/_operations.py (100%) delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/version.py diff --git a/src/k8s-config/HISTORY.rst b/src/k8s-config/HISTORY.rst deleted file mode 100644 index 13b4a515dad..00000000000 --- a/src/k8s-config/HISTORY.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. :changelog: - -Release History -=============== - -0.1.0 -++++++ - -* Release k8s-config with flux configuration support \ No newline at end of file diff --git a/src/k8s-config/README.rst b/src/k8s-config/README.rst deleted file mode 100644 index 744151c134d..00000000000 --- a/src/k8s-config/README.rst +++ /dev/null @@ -1,5 +0,0 @@ -Microsoft Azure CLI 'k8s-config' Extension -========================================== - -This package is for the 'k8s-config' extension. -i.e. 'az k8s-config' \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/__init__.py b/src/k8s-config/azext_k8s_config/__init__.py deleted file mode 100644 index f2363957f9e..00000000000 --- a/src/k8s-config/azext_k8s_config/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from azure.cli.core import AzCommandsLoader - -from azext_k8s_config._help import helps # pylint: disable=unused-import - - -class k8s_configCommandsLoader(AzCommandsLoader): - - def __init__(self, cli_ctx=None): - from azure.cli.core.commands import CliCommandType - from azext_k8s_config._client_factory import k8s_config_client - k8s_config_custom = CliCommandType( - operations_tmpl='azext_k8s_config.custom#{}', - client_factory=k8s_config_client) - super().__init__(cli_ctx=cli_ctx, - custom_command_type=k8s_config_custom) - - def load_command_table(self, args): - from azext_k8s_config.commands import load_command_table - load_command_table(self, args) - return self.command_table - - def load_arguments(self, command): - from azext_k8s_config._params import load_arguments - load_arguments(self, command) - - -COMMAND_LOADER_CLS = k8s_configCommandsLoader diff --git a/src/k8s-config/azext_k8s_config/_client_factory.py b/src/k8s-config/azext_k8s_config/_client_factory.py deleted file mode 100644 index a67cd99b59a..00000000000 --- a/src/k8s-config/azext_k8s_config/_client_factory.py +++ /dev/null @@ -1,45 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from azure.cli.core.commands.client_factory import get_mgmt_service_client -from azure.cli.core.profiles import ResourceType -from . import consts - - -def k8s_config_client(cli_ctx, **kwargs): - from azext_k8s_config.vendored_sdks import SourceControlConfigurationClient - return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient, **kwargs) - - -def k8s_config_fluxconfig_client(cli_ctx, *_): - return k8s_config_client(cli_ctx, api_version=consts.FLUXCONFIG_API_VERSION).flux_configurations - - -def k8s_config_sourcecontrol_client(cli_ctx, *_): - return k8s_config_client(cli_ctx, api_version=consts.SOURCE_CONTROL_API_VERSION).source_control_configurations - - -def k8s_config_extension_client(cli_ctx, *_): - return k8s_config_client(cli_ctx, api_version=consts.EXTENSION_API_VERSION).extensions - - -def resource_providers_client(cli_ctx): - from azure.mgmt.resource import ResourceManagementClient - return get_mgmt_service_client(cli_ctx, ResourceManagementClient).providers - - -def cf_resource_groups(cli_ctx, subscription_id=None): - return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, - subscription_id=subscription_id).resource_groups - - -def cf_resources(cli_ctx, subscription_id=None): - return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, - subscription_id=subscription_id).resources - - -def cf_log_analytics(cli_ctx, subscription_id=None): - from azure.mgmt.loganalytics import LogAnalyticsManagementClient # pylint: disable=no-name-in-module - return get_mgmt_service_client(cli_ctx, LogAnalyticsManagementClient, subscription_id=subscription_id) diff --git a/src/k8s-config/azext_k8s_config/_help.py b/src/k8s-config/azext_k8s_config/_help.py deleted file mode 100644 index 31466d7c818..00000000000 --- a/src/k8s-config/azext_k8s_config/_help.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from knack.help_files import helps # pylint: disable=unused-import - -helps['k8s-config'] = """ - type: group - short-summary: Commands to manage resources from Microsoft.KubernetesConfiguration. -""" - -helps['k8s-config flux'] = """ - type: group - short-summary: Commands to manage Flux Configurations. -""" - -helps['k8s-config flux create'] = """ - type: command - short-summary: Create a Kubernetes Flux Configuration. - examples: - - name: Create a Kubernetes Flux Configuration - text: |- - az k8s-config flux create --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ - --kind git --url https://github.com/Azure/arc-k8s-demo --branch master --kustomization \\ - name=my-kustomization -""" - -helps['k8s-config flux list'] = """ - type: command - short-summary: List Kubernetes Flux Configurations. - examples: - - name: List all Kubernetes Flux Configurations on a cluster - text: |- - az k8s-config flux list --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters -""" - -helps['k8s-config flux show'] = """ - type: command - short-summary: Show a Kubernetes Flux Configuration. - examples: - - name: Show details of a Kubernetes Flux Configuration - text: |- - az k8s-config flux show --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters --name myconfig -""" - -helps['k8s-config flux delete'] = """ - type: command - short-summary: Delete a Kubernetes Flux Configuration. - examples: - - name: Delete an existing Kubernetes Flux Configuration - text: |- - az k8s-config flux delete --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters --name myconfig -""" - -helps['k8s-config extension'] = """ - type: group - short-summary: Commands to manage Kubernetes Extensions. -""" - -helps['k8s-config extension create'] = """ - type: command - short-summary: Create a Kubernetes Extension. - examples: - - name: Create a Kubernetes Extension - text: |- - az k8s-config extension create --resource-group my-resource-group \\ - --cluster-name mycluster --cluster-type connectedClusters \\ - --name myextension --extension-type microsoft.openservicemesh \\ - --scope cluster --release-train stable -""" - -helps['k8s-config extension list'] = """ - type: command - short-summary: List Kubernetes Extensions. - examples: - - name: List all Kubernetes Extensions on a cluster - text: |- - az k8s-config extension list --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters -""" - -helps['k8s-config extension show'] = """ - type: command - short-summary: Show a Kubernetes Extension. - examples: - - name: Show details of a Kubernetes Extension - text: |- - az k8s-config extension show --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters --name myextension -""" - -helps['k8s-config extension delete'] = """ - type: command - short-summary: Delete a Kubernetes Extension. - examples: - - name: Delete an existing Kubernetes Extension - text: |- - az k8s-config extension delete --resource-group my-resource-group --cluster-name mycluster \\ - --cluster-type connectedClusters --name myextension -""" diff --git a/src/k8s-config/azext_k8s_config/_params.py b/src/k8s-config/azext_k8s_config/_params.py deleted file mode 100644 index 7b44aea50af..00000000000 --- a/src/k8s-config/azext_k8s_config/_params.py +++ /dev/null @@ -1,295 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint: disable=line-too-long -# pylint: disable=too-many-statements - -from azure.cli.core.commands.validators import get_default_location_from_resource_group -from azure.cli.core.commands.parameters import ( - get_enum_type, - get_three_state_flag, - tags_type -) -from .validators import validate_extension_name, validate_fluxconfig_name, validate_namespace -from .action import ( - KustomizationAddAction, - AddConfigurationProtectedSettings, - AddConfigurationSettings -) -from . import consts - - -def load_arguments(self, _): - with self.argument_context('k8s-config') as c: - c.argument('tags', tags_type) - c.argument('location', validator=get_default_location_from_resource_group) - c.argument('cluster_name', - options_list=['--cluster-name', '-c'], - help='Name of the Kubernetes cluster') - c.argument('cluster_type', - options_list=['--cluster-type', '-t'], - arg_type=get_enum_type(['connectedClusters', 'managedClusters']), - help='Specify Arc connected clusters or AKS managed clusters.') - - with self.argument_context('k8s-config flux') as c: - c.argument('name', - options_list=['--name', '-n'], - help='Name of the flux configuration', - validator=validate_fluxconfig_name) - - with self.argument_context('k8s-config flux create') as c: - c.argument('scope', - options_list=['--scope', '-s'], - arg_type=get_enum_type(['namespace', 'cluster']), - help="Specify scope of the operator to be 'namespace' or 'cluster'") - c.argument('namespace', - help='Namespace to deploy the configuration', - options_list=['--namespace', '--ns'], - validator=validate_namespace) - c.argument('kind', - arg_type=get_enum_type([consts.GIT]), - help='Source kind to reconcile') - c.argument('url', - options_list=['--url', '-u'], - help='URL of the git repo source to reconcile') - c.argument('timeout', - help='Maximum time to reconcile the source before timing out') - c.argument('sync_interval', - options_list=['--interval', '--sync-interval'], - help='Time between reconciliations of the source on the cluster') - c.argument('branch', - arg_group="Git Repo Ref", - help='Branch within the git source to reconcile with the cluster') - c.argument('tag', - arg_group="Git Repo Ref", - help='Tag within the git source to reconcile with the cluster') - c.argument('semver', - arg_group="Git Repo Ref", - help='Semver range within the git source to reconcile with the cluster') - c.argument('commit', - arg_group="Git Repo Ref", - help='Commit within the git source to reconcile with the cluster') - c.argument('ssh_private_key', - arg_group="Auth", - help='Base64-encoded private ssh key for private repository sync') - c.argument('ssh_private_key_file', - arg_group="Auth", - help='Filepath to private ssh key for private repository sync') - c.argument('https_user', - arg_group="Auth", - help='HTTPS username for private repository sync') - c.argument('https_key', - arg_group="Auth", - help='HTTPS token/password for private repository sync') - c.argument('known_hosts', - arg_group="Auth", - help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') - c.argument('known_hosts_file', - arg_group="Auth", - help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') - c.argument('local_auth_ref', - options_list=['--local-auth-ref', '--local-ref'], - arg_group="Auth", - help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') - c.argument('suspend', - help='Suspend the reconciliation of the source and kustomizations associated with this configuration') - c.argument('kustomization', - action=KustomizationAddAction, - help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", - nargs='+') - - with self.argument_context('k8s-config flux delete') as c: - c.argument('force', - help='Specify whether to force delete the flux configuration from the cluster.') - - with self.argument_context('k8s-config extension') as c: - c.argument('name', - options_list=['--name', '-n'], - help='Name of the extension', - validator=validate_extension_name) - - with self.argument_context('k8s-config extension create') as c: - c.argument('extension_type', - help='Name of the extension type.') - c.argument('scope', - arg_type=get_enum_type(['cluster', 'namespace']), - help='Specify the extension scope.') - c.argument('auto_upgrade_minor_version', - arg_group="Version", - options_list=['--auto-upgrade-minor-version', '--auto-upgrade'], - arg_type=get_three_state_flag(), - help='Automatically upgrade minor version of the extension instance.') - c.argument('version', - arg_group="Version", - help='Specify the version to install for the extension instance if' - ' --auto-upgrade-minor-version is not enabled.') - c.argument('release_train', - arg_group="Version", - help='Specify the release train for the extension type.') - c.argument('configuration_settings', - arg_group="Configuration", - options_list=['--configuration-settings', '--config'], - action=AddConfigurationSettings, - nargs='+', - help='Configuration Settings as key=value pair. Repeat parameter for each setting') - c.argument('configuration_protected_settings', - arg_group="Configuration", - options_list=['--configuration-protected-settings', '--config-protected'], - action=AddConfigurationProtectedSettings, - nargs='+', - help='Configuration Protected Settings as key=value pair. Repeat parameter for each setting') - c.argument('configuration_settings_file', - arg_group="Configuration", - options_list=['--configuration-settings-file', '--config-file'], - help='JSON file path for configuration-settings') - c.argument('configuration_protected_settings_file', - arg_group="Configuration", - options_list=['--configuration-protected-settings-file', '--config-protected-file'], - help='JSON file path for configuration-protected-settings') - c.argument('release_namespace', - help='Specify the namespace to install the extension release.') - c.argument('target_namespace', - help='Specify the target namespace to install to for the extension instance. This' - ' parameter is required if extension scope is set to \'namespace\'') - - with self.argument_context('k8s-config extension delete') as c: - c.argument('force', - help='Specify whether to force delete the extension from the cluster.') - - # with self.argument_context('k8s-config fluxv1') as c: - # c.argument('name', - # options_list=['--name', '-n'], - # help='Name of the configuration', - # validator=validate_configuration_name) - - # with self.argument_context('k8s-config fluxv1 create') as c: - # c.argument('repository_url', - # options_list=['--repository-url', '-u'], - # help='Url of the source control repository') - # c.argument('scope', - # arg_type=get_enum_type(['namespace', 'cluster']), - # help='''Specify scope of the operator to be 'namespace' or 'cluster' ''') - # c.argument('enable_helm_operator', - # arg_group="Helm Operator", - # arg_type=get_three_state_flag(), - # options_list=['--enable-helm-operator', '--enable-hop'], - # help='Enable support for Helm chart deployments') - # c.argument('helm_operator_params', - # arg_group="Helm Operator", - # options_list=['--helm-operator-params', '--hop-params'], - # help='Chart values for the Helm Operator (if enabled)') - # c.argument('helm_operator_chart_version', - # arg_group="Helm Operator", - # options_list=['--helm-operator-chart-version', '--hop-chart-version'], - # help='Chart version of the Helm Operator (if enabled)') - # c.argument('operator_params', - # arg_group="Operator", - # help='Parameters for the Operator') - # c.argument('operator_instance_name', - # arg_group="Operator", - # help='Instance name of the Operator', - # validator=validate_operator_instance_name) - # c.argument('operator_namespace', - # arg_group="Operator", - # help='Namespace in which to install the Operator', - # validator=validate_operator_namespace) - # c.argument('operator_type', - # arg_group="Operator", - # help='''Type of the operator. Valid value is 'flux' ''') - # c.argument('ssh_private_key', - # arg_group="Auth", - # help='Specify Base64-encoded private ssh key for private repository sync') - # c.argument('ssh_private_key_file', - # arg_group="Auth", - # help='Specify filepath to private ssh key for private repository sync') - # c.argument('https_user', - # arg_group="Auth", - # help='Specify HTTPS username for private repository sync') - # c.argument('https_key', - # arg_group="Auth", - # help='Specify HTTPS token/password for private repository sync') - # c.argument('ssh_known_hosts', - # arg_group="Auth", - # help='Specify Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances') - # c.argument('ssh_known_hosts_file', - # arg_group="Auth", - # help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') - - with self.argument_context('k8s-config flux source') as c: - c.argument('scope', - options_list=['--scope', '-s'], - arg_type=get_enum_type(['namespace', 'cluster']), - help="Specify scope of the operator to be 'namespace' or 'cluster'") - c.argument('namespace', - help='Namespace to deploy the configuration', - options_list=['--namespace', '--ns'], - validator=validate_namespace) - c.argument('kind', - arg_type=get_enum_type([consts.GIT]), - help='Source kind to reconcile') - c.argument('url', - options_list=['--url', '-u'], - help='URL of the source to reconcile') - c.argument('timeout', - help='Maximum time to reconcile the source before timing out') - c.argument('sync_interval', - options_list=['--interval', '--sync-interval'], - help='Time between reconciliations of the source on the cluster') - c.argument('branch', - arg_group="Repo Ref", - help='Branch to reconcile with the git source') - c.argument('tag', - arg_group="Repo Ref", - help='Tag to reconcile with the git source') - c.argument('semver', - arg_group="Repo Ref", - help='Semver range to reconcile with the git source') - c.argument('commit', - arg_group="Repo Ref", - help='Specific commit to reconcile with the git source') - c.argument('ssh_private_key', - arg_group="Auth", - help='Base64-encoded private ssh key for private repository sync') - c.argument('ssh_private_key_file', - arg_group="Auth", - help='Filepath to private ssh key for private repository sync') - c.argument('https_user', - arg_group="Auth", - help='HTTPS username for private repository sync') - c.argument('https_key', - arg_group="Auth", - help='HTTPS token/password for private repository sync') - c.argument('known_hosts', - arg_group="Auth", - help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') - c.argument('known_hosts_file', - arg_group="Auth", - help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') - c.argument('local_auth_ref', - options_list=['--local-auth-ref'], - arg_group="Auth", - help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') - - with self.argument_context('k8s-config flux kustomization') as c: - c.argument('kustomization_name', - help='Specify the name of the kustomization to add to the configuration') - c.argument('path', - help='Specify the path in the source that the kustomization should apply') - c.argument('dependencies', - options_list=['--depends', '--dependencies'], - help='Specify the names of kustomization dependencies') - c.argument('timeout', - help='Maximum time to reconcile the kustomization before timing out') - c.argument('sync_interval', - options_list=['--interval', '--sync-interval'], - help='Time between reconciliations of the kustomization on the cluster') - c.argument('retry_interval', - help='Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval') - c.argument('prune', - help='Whether to garbage collect resources deployed by the kustomization on the cluster') - c.argument('force', - help='Whether to re-create resources that cannot be updated on the cluster (i.e. jobs)') - c.argument('validation', - arg_type=get_enum_type(['none', 'client', 'server']), - help='Specify whether to dry-run manifests at the client or at the apiserver level before applying them to the cluster.') diff --git a/src/k8s-config/azext_k8s_config/azext_metadata.json b/src/k8s-config/azext_k8s_config/azext_metadata.json deleted file mode 100644 index 9a4dbb92de4..00000000000 --- a/src/k8s-config/azext_k8s_config/azext_metadata.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "azext.minCliCoreVersion": "2.15.0", - "azext.isPreview": true, - "azext.isExperimental": true -} \ No newline at end of file diff --git a/src/k8s-config/azext_k8s_config/commands.py b/src/k8s-config/azext_k8s_config/commands.py deleted file mode 100644 index 1738bd9cd6f..00000000000 --- a/src/k8s-config/azext_k8s_config/commands.py +++ /dev/null @@ -1,43 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=line-too-long -from azure.cli.core.commands import CliCommandType -from azext_k8s_config._client_factory import ( - k8s_config_fluxconfig_client, - k8s_config_extension_client -) -from .format import ( - fluxconfig_list_table_format, - fluxconfig_show_table_format, - extension_list_table_format, - extension_show_table_format -) - - -def load_command_table(self, _): - k8s_config_fluxconfig_sdk = CliCommandType( - operations_tmpl='azext_k8s_config.vendored_sdks.operations#FluxConfigurationsOperations.{}', - client_factory=k8s_config_fluxconfig_client - ) - - k8s_config_extension_sdk = CliCommandType( - operations_tmpl='azext_k8s_config.vendored_sdks.operations#ExtensionsOperations.{}', - client_factory=k8s_config_extension_client - ) - - with self.command_group('k8s-config flux', k8s_config_fluxconfig_sdk, client_factory=k8s_config_fluxconfig_client, is_experimental=True) as g: - g.custom_command('create', 'flux_config_create', supports_no_wait=True) - g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) - g.custom_show_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) - g.custom_command('delete', 'flux_config_delete', confirmation=True, supports_no_wait=True) - # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) - # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) - - with self.command_group('k8s-config extension', k8s_config_extension_sdk, client_factory=k8s_config_extension_client, is_preview=True) as g: - g.custom_command('create', 'extension_create', supports_no_wait=True) - g.custom_command('list', "extension_list", table_transformer=extension_list_table_format) - g.custom_show_command('show', 'extension_show', table_transformer=extension_show_table_format) - g.custom_command('delete', 'extension_delete', confirmation=True, supports_no_wait=True) diff --git a/src/k8s-config/azext_k8s_config/custom.py b/src/k8s-config/azext_k8s_config/custom.py deleted file mode 100644 index 8686638a649..00000000000 --- a/src/k8s-config/azext_k8s_config/custom.py +++ /dev/null @@ -1,93 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument - -from .providers.ExtensionProvider import ExtensionProvider -from .providers.FluxConfigurationProvider import FluxConfigurationProvider -from . import consts - - -# Flux Configuration Methods - -def flux_config_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): - provider = FluxConfigurationProvider(cmd) - return provider.show(resource_group_name, cluster_type, cluster_name, name) - - -def flux_config_list(cmd, client, resource_group_name, cluster_type, cluster_name): - provider = FluxConfigurationProvider(cmd) - return provider.list(resource_group_name, cluster_type, cluster_name) - - -# pylint: disable=too-many-locals -def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, - scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, - branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, - ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, - known_hosts_file=None, suspend=False, kustomization=None, no_wait=False): - - provider = FluxConfigurationProvider(cmd) - return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, - timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, ssh_private_key, - ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, suspend, - kustomization, no_wait) - - -def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, - scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, - branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, - ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, - known_hosts=None, known_hosts_file=None): - - provider = FluxConfigurationProvider(cmd) - return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, - kind, timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, - ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, - known_hosts_file) - - -def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, - kustomization_name, dependencies=None, timeout=None, sync_interval=None, - retry_interval=None, path='', prune=False, validation='none', force=False): - - provider = FluxConfigurationProvider(cmd) - return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, - dependencies, timeout, sync_interval, retry_interval, path, prune, - validation, force) - - -def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False, yes=False): - provider = FluxConfigurationProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait, yes) - - -# Extension Methods - -def extension_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): - provider = ExtensionProvider(cmd) - return provider.show(resource_group_name, cluster_type, cluster_name, name) - - -def extension_list(cmd, client, resource_group_name, cluster_type, cluster_name): - provider = ExtensionProvider(cmd) - return provider.list(resource_group_name, cluster_type, cluster_name) - - -def extension_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, - extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, - version=None, target_namespace=None, release_namespace=None, configuration_settings=None, - configuration_protected_settings=None, configuration_settings_file=None, - configuration_protected_settings_file=None, tags=None, no_wait=False): - provider = ExtensionProvider(cmd) - return provider.create(resource_group_name, cluster_type, cluster_name, name, extension_type, scope, - auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file) - - -def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False): - provider = ExtensionProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait) diff --git a/src/k8s-config/azext_k8s_config/tests/__init__.py b/src/k8s-config/azext_k8s_config/tests/__init__.py deleted file mode 100644 index 99c0f28cd71..00000000000 --- a/src/k8s-config/azext_k8s_config/tests/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# ----------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ----------------------------------------------------------------------------- diff --git a/src/k8s-config/azext_k8s_config/tests/latest/__init__.py b/src/k8s-config/azext_k8s_config/tests/latest/__init__.py deleted file mode 100644 index 99c0f28cd71..00000000000 --- a/src/k8s-config/azext_k8s_config/tests/latest/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# ----------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ----------------------------------------------------------------------------- diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py b/src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py deleted file mode 100644 index dfe285b1e2b..00000000000 --- a/src/k8s-config/azext_k8s_config/tests/latest/test_kubernetesconfiguration_scenario.py +++ /dev/null @@ -1,138 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import os - -from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, record_only) -from azure.cli.core.azclierror import InvalidArgumentValueError, ResourceNotFoundError - -TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) - - -class K8sConfigurationScenarioTest(ScenarioTest): - @ResourceGroupPreparer(name_prefix='cli_test_k8s_configuration') - @record_only() - def test_k8s_configuration_success(self): - - # -------------------------------------------------------------------- - # SSH SCENARIO TEST - # -------------------------------------------------------------------- - self.kwargs.update({ - 'name': 'cli-test-config10', - 'cluster_name': 'nanthicluster0923', - 'rg': 'nanthirg0923', - 'repo_url': 'git://github.com/anubhav929/flux-get-started', - 'operator_instance_name': 'cli-test-config10-opin', - 'operator_namespace': 'cli-test-config10-opns', - 'cluster_type': 'connectedClusters', - 'scope': 'namespace', - 'ssh_private_key': 'LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFZRUFxZlBtNlc3YkVLTmVvN3VCQzhTMXYydUpPS1NZWGNmanlpVEk2djNkZUhRSjJtMGFRajB0CmtwM05qMUZkRUsrMkVXTy9xNGFkWUpaS0ZZSjluWTZyREZOSXBZdmVWaVNUQjhITzI5VVdySTRLVGZMRGhiVmVCV0pjQVcKMkFpZ0ZnTU5qdTZXa0JVL1NWK1FCVHJiRVl6RFhpOTVNR1ZveTVKV3drdkdtakRaOHFSaEFxbU0rdUF4S1I4Z1lyRllPZgpRbC9zM2I5ajJKQ1VtVFlwYkxqMkJPd0JNQ1J3NlFQY0lVcVlaaUl3MUNNaXZKZ2tVQTdwUlRCZHVsYXlXNWQ2MTl4RFNsCmZ6N1JuU0tKM3RwanEwZThBTmtkU1h4SjQrMXhpNm5IM0lVY1ZBM1NzcVhWam80ak5sNU5EWkJlTDNpQ0xXSVZYUkpDemsKNGg3a2pXVkQ3UnNDNGJDOTF6MzlZMDlnK3ZIdjErZFplUmNYZWIvNkFzbTBEeHVhRGo2cVVCVm9JOWkwbzFKbndiMnA0MQpGV2prazljc054a2dnajMzU3ozTWJRTVN0bTFLaWU2bHNRamlMUXdGT3Qwd3lFTnova2RUR25idkVMUTN3aWdUdVFrelFOCnlMR2dmK3FXZnhqL1l1MWt5b0xrQVpqT3JxdEttalVILzk3Y3lncWhBQUFGa08zNi9uWHQrdjUxQUFBQUIzTnphQzF5YzIKRUFBQUdCQUtuejV1bHUyeENqWHFPN2dRdkV0YjlyaVRpa21GM0g0OG9reU9yOTNYaDBDZHB0R2tJOUxaS2R6WTlSWFJDdgp0aEZqdjZ1R25XQ1dTaFdDZloyT3F3eFRTS1dMM2xZa2t3ZkJ6dHZWRnF5T0NrM3l3NFcxWGdWaVhBRnRnSW9CWUREWTd1CmxwQVZQMGxma0FVNjJ4R013MTR2ZVRCbGFNdVNWc0pMeHBvdzJmS2tZUUtwalByZ01Ta2ZJR0t4V0RuMEpmN04yL1k5aVEKbEprMktXeTQ5Z1RzQVRBa2NPa0QzQ0ZLbUdZaU1OUWpJcnlZSkZBTzZVVXdYYnBXc2x1WGV0ZmNRMHBYOCswWjBpaWQ3YQpZNnRIdkFEWkhVbDhTZVB0Y1l1cHg5eUZIRlFOMHJLbDFZNk9JelplVFEyUVhpOTRnaTFpRlYwU1FzNU9JZTVJMWxRKzBiCkF1R3d2ZGM5L1dOUFlQcng3OWZuV1hrWEYzbS8rZ0xKdEE4Ym1nNCtxbEFWYUNQWXRLTlNaOEc5cWVOUlZvNUpQWExEY1oKSUlJOTkwczl6RzBERXJadFNvbnVwYkVJNGkwTUJUcmRNTWhEYy81SFV4cDI3eEMwTjhJb0U3a0pNMERjaXhvSC9xbG44WQovMkx0Wk1xQzVBR1l6cTZyU3BvMUIvL2UzTW9Lb1FBQUFBTUJBQUVBQUFHQkFKSnJUVTlqY0Z4ZlE1UHdZUGRRbS95MG10CjR3QUEwYnY0WlNOcjh0dy9hWWtqeWFybnJPMWtwd3BiNkpySkpKcjZRL3Vjdi9CK3RFejhMRVQ1REViMTBKQzVlRWJ5THMKRTdnbEl5Q0Y3eWp1bnJZVkpwbzFiVEZhVWtYd24wTkdlQ2JkWHNlODdhWDFISmdQemdmZ2dhcTk2aks5ZWtKcXJzQXM4VwpGWjZWNDgrR0N3WU9LU1dpclBmdWx5b3YvQURCOVZJVzdTQ3lWek9uTGRGTWRVZXJBMjI3Y3NUaEtTZnI0MzFDQjU2SE43CmFkdnRmNnR4alV0TXBoTjV5ZVBiRmxVZS9Wb2VQY1hNdXA4OXN3V2gvd3ZScklCbytUYXo2SzQxcGFzOEVObjFyemFxL3kKRHlWelJuSGtlMGhKR2ZZelJhbzlZQm5jeHFMOCtXdDQxZFFzQUdhdlIwd3ZNSit5TFpuR0x5amVXaVZkcExjT0FWSGpIOQpITGMrTDdnaGpIZ1VidDNDWG9Wd0gyWktnelI5cmk3bU93YnorejZsN1pwWjlQalJxeU1HcTloYU5vNHVEdjJqbWhGNlZVClBMU2Q3WTczWCtWTFAvWUZqbTBlUzJUbGFRQ3E2Vms0dzJqSHVWcXorcng4SllYb2tidFZXYnFYcmg3VzF5VGk4MXVRQUEKQU1Ba0JaQzF0SThvd29SNDYvL1h1SWQxQjBGRUhGUXBvSHFuVGNSVlVKS2RXb2xJRU5tYVVtdG1UZFVicVYyNGJMa1RtZQpiWHZQdlF3LzJoVk5VVmhWbDNjays1SUZBS0hYVWJ3ZklSWE8vUVlUbFM0ZVdabkFsN0JQSzJQa080SXkvOG1zQVZKRGl4CmkvVm1oaTBYb05lSmxERU9sdzNaY084aTlRZjVSbTNEWmRHUDRha0JsYmk5ekdBWUpqRGFjM0dWdTMxK2pJVG9hUHplbysKeUFDL2svM0J5Slg4enQ1cDRHVXpsNVFKcEVHMnBpQXdJeElKZS8yK3pBMXU5dmhma0FBQURCQU5NZHdhemx5MXNpd0dXbQpJWSs4VFZMN1EwQ1pFTWxTL0VraE1YM2FNQnZYaURXd2cwVk8zKytXUDhlMWhDSUxvNmdqL0N2dFdLdGEzVlozUWFScHZ5CkhCVEp4Q205NHZQOXFPelhTRGZ0WVRrSHh1SFdQaklhb010N0YyL0srejJiZTdESmhvL0ZwMVY0U2x2R1ljWHdqaWhEaDAKbHF1bUltOEJJei9taHpjZTFKR0VMUUdJeXk4RDI0dTNtY2NhSFoxYWY1V3A5Y1VCZ09POXEwa3B1WVhEdHpPSk9UTVozUQpNUm5xdXVVM1ppRHdmRGltZzdsZktwWGkxZzFxeWZUd0FBQU1FQXpoWEdhTVdBM1pUT1hqWWhPTUhkdTk0R2RNcHNXYWo0CjBsMmZ6YzdFWTlzWEdLZ01XMllvRXk5UVNSTDRPUmNMaUFKTDRLZGdZeGZzeVdma1U1d21TbGZXNjlrb0R2WTE0LzNWbWYKZ0NTUkxvL0RnTUZtOGFNK3pUVzhWYTVpclJXWFpEeHNXb0RiNzdIZ2JZaE90M29iOEFWWUh4akk3N1k3MXlBUzhXS2xRSQpYQi9qZ01vN1BCL3BTMVVYSEhCcndxQkdwM3M5aThab0E0L2hLY0pvaEtWSDZGL0Z2Rk1jWHZTNjZOcGNUWHNWQzBVUzNkCkJVY0taNTVvUUhVcnNQQUFBQUdIQnlZWFJvYVd0eVFFeEJVRlJQVUMxU00wZFVUa2xDVXdFQwotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K', - 'ssh_known_hosts': 'Z2l0b3BzLWJpdGJ1Y2tldC10ZXN0LXNlcnZlci5lYXN0dXMuY2xvdWRhcHAuYXp1cmUuY29tIHNzaC1yc2EgQUFBQUIzTnphQzF5YzJFQUFBQURBUUFCQUFBQkFRQytNT0w3bjk2aGs3emVmMDNwak9vMGF3UENISkZ4NU04TjJ2L2tvODgvc202Y2VzOFljdnYyL0hoUlhRSFZHRUxqZjNuTXVGSVJPMEdMdTFabFNreGRUTUhGcXBxYzFjcUM2R3kveUJXRGM1SWFwWnJBMXFxeSsrZVdpelAzQXdMbWsrMUhXWGdtcHljZUtYNU9vd3VNT3cwd3RYRUdTcDhtVk0wV2VpUzEwWnZ5ZVVKK04zbkNvczMyWDhIeVpnc1pMUS9zSTB4NXN6ODQ2am5JZEFOckZsYU9MUTJ1ejRUa0M2ekNvd3lIdzlLWXJ5V2hJZDAraCt5SXQ5dUtqVHZsWFNpdm1ISjViZzdUWWlkbnFtbjI0UGE4WnFpbTE5UGszUjg0cW9qclVmYm1XT3VwUjdYNXZVVWZqYzhERFRxa3FnRmkxcWdVdE1mWGlMRXErZFVa' - }) - - # Check that the configuration does not already exist - with self.assertRaises(ResourceNotFoundError): - self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}') - - # Create a configuration - self.cmd(''' k8s-configuration create -g {rg} - -n {name} - -c {cluster_name} - -u {repo_url} - --cluster-type {cluster_type} - --scope {scope} - --operator-instance-name {operator_instance_name} - --operator-namespace {operator_namespace} - --operator-params \"--git-readonly \" - --ssh-private-key {ssh_private_key} - --ssh-known-hosts {ssh_known_hosts} - --enable-helm-operator - --helm-operator-chart-version 1.2.0 - --helm-operator-params \"--set git.ssh.secretName=gitops-privatekey-{operator_instance_name} --set tillerNamespace=kube-system\" ''', - checks=[ - self.check('name', '{name}'), - self.check('resourceGroup', '{rg}'), - self.check('operatorInstanceName', '{operator_instance_name}'), - self.check('operatorNamespace', '{operator_namespace}'), - self.check('provisioningState', 'Succeeded'), - self.check('operatorScope', 'namespace'), - self.check('operatorType', 'Flux'), - self.check('sshKnownHostsContents', '{ssh_known_hosts}') - ]) - - # Get the configuration created - self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}', - checks=[ - self.check('name', '{name}'), - self.check('resourceGroup', '{rg}'), - self.check('operatorInstanceName', '{operator_instance_name}'), - self.check('operatorNamespace', '{operator_namespace}'), - self.check('provisioningState', 'Succeeded'), - self.check('operatorScope', 'namespace'), - self.check('operatorType', 'Flux'), - self.check('sshKnownHostsContents', '{ssh_known_hosts}') - ]) - - # Delete the created configuration - self.cmd('k8s-configuration delete -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type} -y') - - # -------------------------------------------------------------------- - # HTTPS SCENARIO TEST - # -------------------------------------------------------------------- - self.kwargs.update({ - 'name': 'cli-test-config11', - 'cluster_name': 'nanthicluster0923', - 'rg': 'nanthirg0923', - 'repo_url': 'https://github.com/jonathan-innis/helm-operator-get-started-private.git', - 'operator_instance_name': 'cli-test-config11-opin', - 'operator_namespace': 'cli-test-config11-opns', - 'cluster_type': 'connectedClusters', - 'scope': 'namespace', - 'https_user': 'fake-username', - 'https_key': 'fakepasswordthatiwoulduseforgithub' - }) - - # Check that the configuration does not already exist - with self.assertRaises(ResourceNotFoundError): - self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}') - - self.cmd(''' k8s-configuration create -g {rg} - -n {name} - -c {cluster_name} - -u {repo_url} - --cluster-type {cluster_type} - --scope {scope} - --operator-instance-name {operator_instance_name} - --operator-namespace {operator_namespace} - --operator-params \"--git-readonly \" - --https-user {https_user} - --https-key {https_key} - --enable-helm-operator - --helm-operator-chart-version 1.2.0 - --helm-operator-params \"--set tillerNamespace=kube-system\" ''', - checks=[ - self.check('name', '{name}'), - self.check('resourceGroup', '{rg}'), - self.check('operatorInstanceName', '{operator_instance_name}'), - self.check('operatorNamespace', '{operator_namespace}'), - self.check('provisioningState', 'Succeeded'), - self.check('operatorScope', 'namespace'), - self.check('operatorType', 'Flux') - ]) - - # Get the configuration created - self.cmd('k8s-configuration show -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type}', - checks=[ - self.check('name', '{name}'), - self.check('resourceGroup', '{rg}'), - self.check('operatorInstanceName', '{operator_instance_name}'), - self.check('operatorNamespace', '{operator_namespace}'), - self.check('provisioningState', 'Succeeded'), - self.check('operatorScope', 'namespace'), - self.check('operatorType', 'Flux'), - ]) - - # Delete the created configuration - self.cmd('k8s-configuration delete -g {rg} -c {cluster_name} -n {name} --cluster-type {cluster_type} -y') diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_validators.py b/src/k8s-config/azext_k8s_config/tests/latest/test_validators.py deleted file mode 100644 index 4e6259d8bf9..00000000000 --- a/src/k8s-config/azext_k8s_config/tests/latest/test_validators.py +++ /dev/null @@ -1,176 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import unittest -import base64 -from azure.cli.core.azclierror import InvalidArgumentValueError, MutuallyExclusiveArgumentError -from azext_k8s_configuration.custom import _get_protected_settings -import azext_k8s_configuration._validators as validators -from Crypto.PublicKey import RSA, ECC, DSA -from paramiko.ed25519key import Ed25519Key - - -class TestValidateKeyTypes(unittest.TestCase): - def test_bad_private_key(self): - private_key_encoded = base64.b64encode("this is not a valid private key".encode('utf-8')).decode('utf-8') - err = "Error! --ssh-private-key provided in invalid format" - with self.assertRaises(InvalidArgumentValueError) as cm: - _get_protected_settings(private_key_encoded, '', '', '') - self.assertEqual(str(cm.exception), err) - - def test_rsa_private_key(self): - rsa_key = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFZRUF1bVA5M09qRHdjdlEyZHZhRlJNNWYrMEhVSnFvOFJnbmdwaGN3NFZidnd1TVNoQTZFc2FyCjFsam1CNUNnT1NGNHJqNDIvcmdxMW1hWndoSUgvckdPSElNa0lIcjFrZmNKMnBrR3ZhK1NxVm4wWUhzMjBpUW02ay92ZXQKdXdVQ2J1QjlxSU5zL2h2b0ppQ21JMUVpVWZ4VGoxRFJCUG15OXR3Qm52bW5FS1kxZ2NhT2YrS2Y1aGhCc09pd00yZnBRTwp0aTlIcHVzM1JhNXpFeElWbjJzVitpRjVvV3ZZM1JQTTlKNXFPMXRObUtOWll6TjgzbDYxMlBzRmR1Vm1QM2NUUlJtK2pzCjdzZW5jY0U0RitzU0hQMlJpMk5DU0JvZ2RJOFR5VTlzeTM3Szl3bFJ5NGZkWWI1K1o3YUZjMjhTNDdDWlo5dTRFVXdWUEYKbjU4dTUzajU0empwdXNpei9ZWmx3MG5NeEQ5SXI0aHlJZ2s0NlUzVmdHR0NPUytZVTVZT2JURGhPRG5udk5VRkg2NVhCagpEM3l6WVJuRDA3b2swQ1JUR3RCOWMzTjBFNDBjUnlPeVpEQ0l5a0FPdHZXYnBUZzdnaXA2UDc4K2pLVlFnanFwRTVQdi9ICnl1dlB6cUJoUkpWcG5VR1dvWnFlcWJhd2N5RWZwdHFLaTNtWUdVMHBBQUFGa0U5cUs3SlBhaXV5QUFBQUIzTnphQzF5YzIKRUFBQUdCQUxwai9kem93OEhMME5uYjJoVVRPWC90QjFDYXFQRVlKNEtZWE1PRlc3OExqRW9RT2hMR3E5Wlk1Z2VRb0RraAplSzQrTnY2NEt0Wm1tY0lTQi82eGpoeURKQ0I2OVpIM0NkcVpCcjJ2a3FsWjlHQjdOdElrSnVwUDczcmJzRkFtN2dmYWlECmJQNGI2Q1lncGlOUklsSDhVNDlRMFFUNXN2YmNBWjc1cHhDbU5ZSEdqbi9pbitZWVFiRG9zRE5uNlVEcll2UjZick4wV3UKY3hNU0ZaOXJGZm9oZWFGcjJOMFR6UFNlYWp0YlRaaWpXV016Zk41ZXRkajdCWGJsWmo5M0UwVVp2bzdPN0hwM0hCT0JmcgpFaHo5a1l0alFrZ2FJSFNQRThsUGJNdCt5dmNKVWN1SDNXRytmbWUyaFhOdkV1T3dtV2ZidUJGTUZUeForZkx1ZDQrZU00CjZicklzLzJHWmNOSnpNUS9TSytJY2lJSk9PbE4xWUJoZ2prdm1GT1dEbTB3NFRnNTU3elZCUit1VndZdzk4czJFWnc5TzYKSk5Ba1V4clFmWE56ZEJPTkhFY2pzbVF3aU1wQURyYjFtNlU0TzRJcWVqKy9Qb3lsVUlJNnFST1Q3L3g4cnJ6ODZnWVVTVgphWjFCbHFHYW5xbTJzSE1oSDZiYWlvdDVtQmxOS1FBQUFBTUJBQUVBQUFHQkFMaElmSXFacUZKSFRXcllyN24rays4alR3ClFtcGJvWmc1YmZSWGdhdGljaEo4ZGlXOGlNblFFRVRBcFd0OU5FZ0tqbDRrSGRuSnoyUERkZzFIN0ExaHppbkNsdzZMTTAKYUkyMGxyR2NrWWpXNDRNd3ozYmRQNHlURTllSXRiM0pmN1pNSGpqek4rSy96bWN0eWdMeXFZSzVXYTljM1JnMXdIRWFNNAplakUvNDg4M25WUmJvSFJDcjFCVi8wQVVFTTZhNisrRHpVZW9WdWdWL3RsV3RVMlJuQlZ4eCtJS0FVSDZRTHJFU2JkUkRoCkVGUEFhRWtEb3crd3dDcFpqTXBhMHdRZXBDSkhwWkJLN1pBU25EU3R3Y2RKRE4yeHZzdVNOOGg0bkN0MlZWd0xRenJKeVAKU2VjcWM3M1hIc3E3VWx6ZU5veHlTVW9KZ2JjNTZoRzhWYS9ITlhsOUtkdkFlWUVzS1l1OW5NRUprVSt3VHo1KzUvM2wwVQpxSkErb0pTVTducjYydlVKQnljbXg0SFdBcjJ6QkR2QnFBUWMzRG9LWHczeVM1Z0c5Zkc0c25OUUkxOHVRSjdOSjdndHZHClpKRU56bTNJMmFTMzl5dndWZnFIMXpXVERxU2VNeWhYeWFnTkFEcGtCVEJIMVJQR2NtTFplclFmWWx1djVVUmFNTXdRQUEKQU1BdE9oNHFwUUhidm5tQ1RVakx4dXRrWnRaRlhNa0hmSTk5NS9Nd2RvWVY1eWRKV0pUVGsyKzB1QVBIcTZEejk2b3dWbQpjUkF2WDBDOVU5d3ZRMkpnR0Y1MDZzcmgzZkVpUzM2d1ArOFd0RjZ6ODd0enJwQnpQVHIxOGRONURCOEx5L3dXRk5BVTdqClBUbXM0dHlUY1VsRXR3eEt4TXJTNC9ROUZwMWozL3JNdnNZdGVaSVgycmN4YUhkWWJDVGJtTUpZS3lVTWVXTk56NXpub1EKcFcyd2NDSmpJc1MvS1F2WmR4cHZwNWd0RXE1WlEva3FvLzJVRWd1NHhwdDNWeUNma0FBQURCQVBOSHVEU1R0ZEpJWjdzcwpaQkVwcUE4TE54b1dMQ2RURnlpRERiUnpYOWVPTldkRFQ3NklaRE9HejczNXJhZUFSM2FiY0FhaUM0dDQwTFJTNGEyN29sCm9wK1dSak9wcjVNYUtOUnk4MCt6VWw3WUlSMjErKzVnMFVnNkRnQlBEdmFJSHFSTnRsZ2gyVXdTL0cva1lOaUlEY0JiS1EKOUcvdTI4ekRIRUtNL21YYS8wYnFtSm16ZUYvY1BLdHdScFE3clFoRnAwUkdFcnZtc0l4dDl6K0ZZZUdncjFBYUVTV0ZlTApmUmZsa0lnOVBWOEl0b09GN25qK2VtMkxkNTNCS1hSUUFBQU1FQXhDTFBueHFFVEsyMW5QOXFxQVYzMEZUUkhGNW9kRHg4ClpiYnZIbjgwdEgxQjYwZjRtTGJFRm56REZFR0NwS2Rwb3dyUXR6WUhnQzNBaGNJUE9BbXFXaDg0UEFPbisreHhFanNaQkwKRWhVWmNFUndkYTMzTnJDNTVEMzZxbDBMZEsrSGRuZUFzVGZhazh0bWVlOTJWb0RxdWovNGFSMjBmUTBJUFVzMU8rWHNRNQpGWVFYQzZndExHZGRzRVFoSDF6MTh6RGtWa1UwdEhlZkJaL2pFZXBiOEZScXoxR1hpT0hGK2xBZVE2b3crS0xlcWtCcXQ4CkZxMHhGdG90SlF4VnFWQUFBQUYycHZhVzV1YVhOQVJFVlRTMVJQVUMxUVRWVkdVRFpOQVFJRAotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K" - protected_settings = _get_protected_settings(rsa_key, '', '', '') - self.assertEqual('sshPrivateKey' in protected_settings, True) - self.assertEqual(protected_settings.get('sshPrivateKey'), rsa_key) - - def test_dsa_private_key(self): - key = DSA.generate(2048) - private_key_encoded = base64.b64encode(key.export_key()).decode('utf-8') - protected_settings = _get_protected_settings(private_key_encoded, '', '', '') - self.assertEqual('sshPrivateKey' in protected_settings, True) - self.assertEqual(protected_settings.get('sshPrivateKey'), private_key_encoded) - - def test_ecdsa_private_key(self): - ecdsa_key = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFhQUFBQUJObFkyUnpZUwoxemFHRXlMVzVwYzNSd01qVTJBQUFBQ0c1cGMzUndNalUyQUFBQVFRUjBRc1BjWmJKeWZPaXE2a1M1d0VaeE5DbmR2YVJHCm1ETEUvVVBjakpDTDZQTVIyZmdPS2NnWlhzTEZkTUFzSnExS2d6TmNDN0ZXNGE0L0wrYTFWWUxDQUFBQXNIZ1RqTFY0RTQKeTFBQUFBRTJWalpITmhMWE5vWVRJdGJtbHpkSEF5TlRZQUFBQUlibWx6ZEhBeU5UWUFBQUJCQkhSQ3c5eGxzbko4NktycQpSTG5BUm5FMEtkMjlwRWFZTXNUOVE5eU1rSXZvOHhIWitBNHB5Qmxld3NWMHdDd21yVXFETTF3THNWYmhyajh2NXJWVmdzCklBQUFBZ0h1U3laU0NUZzJZbVNpOG9aY2c0cnVpODh0T1NUSm1aRVhkR09hdExySHNBQUFBWGFtOXBibTVwYzBCRVJWTkwKVkU5UUxWQk5WVVpRTmswQgotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K" - protected_settings = _get_protected_settings(ecdsa_key, '', '', '') - self.assertEqual('sshPrivateKey' in protected_settings, True) - self.assertEqual(protected_settings.get('sshPrivateKey'), ecdsa_key) - - def test_ed25519_private_key(self): - ed25519_key = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFNd0FBQUF0emMyZ3RaVwpReU5UVXhPUUFBQUNCNjF0RzkrNGFmOTZsWGoyUStjWjJMT2JpV1liMlRtWVR6N3NSV0JDM1hVZ0FBQUtCRzFWRWZSdFZSCkh3QUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQjYxdEc5KzRhZjk2bFhqMlErY1oyTE9iaVdZYjJUbVlUejdzUldCQzNYVWcKQUFBRURRTStLcCtOSWpJVUhSUklqRFE5VDZ0U0V0SG9Ic0w1QjlwbHpCNlZ2MnluclcwYjM3aHAvM3FWZVBaRDV4bllzNQp1SlpodlpPWmhQUHV4RllFTGRkU0FBQUFGMnB2YVc1dWFYTkFSRVZUUzFSUFVDMVFUVlZHVURaTkFRSURCQVVHCi0tLS0tRU5EIE9QRU5TU0ggUFJJVkFURSBLRVktLS0tLQo=" - protected_settings = _get_protected_settings(ed25519_key, '', '', '') - self.assertEqual('sshPrivateKey' in protected_settings, True) - self.assertEqual(protected_settings.get('sshPrivateKey'), ed25519_key) - - -class TestValidateK8sNaming(unittest.TestCase): - def test_long_operator_namespace(self): - operator_namespace = "thisisaverylongnamethatistoolongtobeused" - namespace = OperatorNamespace(operator_namespace) - err = 'Error! Invalid --operator-namespace' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_operator_namespace(namespace) - self.assertEqual(str(cm.exception), err) - - def test_long_operator_instance_name(self): - operator_instance_name = "thisisaverylongnamethatistoolongtobeused" - namespace = OperatorInstanceName(operator_instance_name) - err = 'Error! Invalid --operator-instance-name' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_operator_instance_name(namespace) - self.assertEqual(str(cm.exception), err) - - def test_caps_operator_namespace(self): - operator_namespace = 'Myoperatornamespace' - namespace = OperatorNamespace(operator_namespace) - err = 'Error! Invalid --operator-namespace' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_operator_namespace(namespace) - self.assertEqual(str(cm.exception), err) - - def test_caps_operator_instance_name(self): - operator_instance_name = 'Myoperatorname' - namespace = OperatorInstanceName(operator_instance_name) - err = 'Error! Invalid --operator-instance-name' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_operator_instance_name(namespace) - self.assertEqual(str(cm.exception), err) - - def test_long_config_name(self): - config_name = "thisisaverylongnamethatistoolongtobeusedthisisaverylongnamethatistoolongtobeused" - err = 'Error! Invalid --name' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_configuration_name(config_name) - self.assertEqual(str(cm.exception), err) - - def test_valid_config_name(self): - config_name = "this-is-a-valid-config" - validators._validate_configuration_name(config_name) - - def test_caps_config_name(self): - config_name = "ThisIsaCapsConfigName" - err = 'Error! Invalid --name' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_configuration_name(config_name) - self.assertEqual(str(cm.exception), err) - - def test_dot_config_name(self): - config_name = "a234567890b234567890c234567890d234567890e234567890f234567890.23" - err = 'Error! Invalid --name' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_configuration_name(config_name) - self.assertEqual(str(cm.exception), err) - - def test_end_hyphen_config_name(self): - config_name = "a234567890b234567890c234567890d234567890e234567890f23456789023-" - err = 'Error! Invalid --name' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_configuration_name(config_name) - self.assertEqual(str(cm.exception), err) - - -class TestValidateURLWithParams(unittest.TestCase): - def test_ssh_private_key_with_ssh_url(self): - validators._validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', True, False, False) - - def test_ssh_known_hosts_with_ssh_url(self): - validators._validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', False, True, False) - - def test_https_auth_with_https_url(self): - validators._validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', False, False, True) - - def test_ssh_private_key_with_https_url(self): - err = 'Error! An --ssh-private-key cannot be used with an http(s) url' - with self.assertRaises(MutuallyExclusiveArgumentError) as cm: - validators._validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', True, False, False) - self.assertEqual(str(cm.exception), err) - - def test_ssh_known_hosts_with_https_url(self): - err = 'Error! --ssh-known-hosts cannot be used with an http(s) url' - with self.assertRaises(MutuallyExclusiveArgumentError) as cm: - validators._validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', False, True, False) - self.assertEqual(str(cm.exception), err) - - def test_https_auth_with_ssh_url(self): - err = 'Error! https auth (--https-user and --https-key) cannot be used with a non-http(s) url' - with self.assertRaises(MutuallyExclusiveArgumentError) as cm: - validators._validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', False, False, True) - self.assertEqual(str(cm.exception), err) - - -class TestValidateKnownHosts(unittest.TestCase): - def test_valid_known_hosts(self): - known_hosts_raw = "ssh.dev.azure.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4NakVyIzf1rXYd4d7wo6jBlkLvCA4odBlL0mDUyZ0/QUfTTqeu+tm22gOsv+VrVTMk6vwRU75gY/y9ut5Mb3bR5BV58dKXyq9A9UeB5Cakehn5Zgm6x1mKoVyf+FFn26iYqXJRgzIZZcZ5V6hrE0Qg39kZm4az48o0AUbf6Sp4SLdvnuMa2sVNwHBboS7EJkm57XQPVU3/QpyNLHbWDdzwtrlS+ez30S3AdYhLKEOxAG8weOnyrtLJAUen9mTkol8oII1edf7mWWbWVf0nBmly21+nZcmCTISQBtdcyPaEno7fFQMDD26/s0lfKob4Kw8H" - known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') - validators._validate_known_hosts(known_hosts_encoded) - - def test_valid_known_hosts_with_comment(self): - known_hosts_raw = "ssh.dev.azure.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4NakVyIzf1rXYd4d7wo6jBlkLvCA4odBlL0mDUyZ0/QUfTTqeu+tm22gOsv+VrVTMk6vwRU75gY/y9ut5Mb3bR5BV58dKXyq9A9UeB5Cakehn5Zgm6x1mKoVyf+FFn26iYqXJRgzIZZcZ5V6hrE0Qg39kZm4az48o0AUbf6Sp4SLdvnuMa2sVNwHBboS7EJkm57XQPVU3/QpyNLHbWDdzwtrlS+ez30S3AdYhLKEOxAG8weOnyrtLJAUen9mTkol8oII1edf7mWWbWVf0nBmly21+nZcmCTISQBtdcyPaEno7fFQMDD26/s0lfKob4Kw8H ThisIsAValidComment" - known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') - validators._validate_known_hosts(known_hosts_encoded) - - def test_valid_known_hosts_with_comment_own_line(self): - known_hosts_raw = "#this is a comment on its own line\nssh.dev.azure.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7Hr1oTWqNqOlzGJOfGJ4NakVyIzf1rXYd4d7wo6jBlkLvCA4odBlL0mDUyZ0/QUfTTqeu+tm22gOsv+VrVTMk6vwRU75gY/y9ut5Mb3bR5BV58dKXyq9A9UeB5Cakehn5Zgm6x1mKoVyf+FFn26iYqXJRgzIZZcZ5V6hrE0Qg39kZm4az48o0AUbf6Sp4SLdvnuMa2sVNwHBboS7EJkm57XQPVU3/QpyNLHbWDdzwtrlS+ez30S3AdYhLKEOxAG8weOnyrtLJAUen9mTkol8oII1edf7mWWbWVf0nBmly21+nZcmCTISQBtdcyPaEno7fFQMDD26/s0lfKob4Kw8H" - known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') - validators._validate_known_hosts(known_hosts_encoded) - - def test_invalid_known_hosts(self): - known_hosts_raw = "thisisabadknownhostsfilethatisaninvalidformat" - known_hosts_encoded = base64.b64encode(known_hosts_raw.encode('utf-8')).decode('utf-8') - err = 'Error! ssh known_hosts provided in wrong format' - with self.assertRaises(InvalidArgumentValueError) as cm: - validators._validate_known_hosts(known_hosts_encoded) - self.assertEqual(str(cm.exception), err) - - -class OperatorNamespace: - def __init__(self, operator_namespace): - self.operator_namespace = operator_namespace - - -class OperatorInstanceName: - def __init__(self, operator_instance_name): - self.operator_instance_name = operator_instance_name diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py b/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py deleted file mode 100644 index b0a136e072d..00000000000 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._source_control_configuration_client import SourceControlConfigurationClient -__all__ = ['SourceControlConfigurationClient'] - -try: - from ._patch import patch_sdk # type: ignore - patch_sdk() -except ImportError: - pass diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py deleted file mode 100644 index d6b853c02a3..00000000000 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/_configuration.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- -from typing import TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any - - from azure.core.credentials import TokenCredential - -class SourceControlConfigurationClientConfiguration(Configuration): - """Configuration for SourceControlConfigurationClient. - - 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. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). - :type subscription_id: str - """ - - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) - - self.credential = credential - self.subscription_id = subscription_id - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'azure-mgmt-kubernetesconfiguration/{}'.format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') - if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py b/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py deleted file mode 100644 index 825bb82bbfe..00000000000 --- a/src/k8s-config/azext_k8s_config/vendored_sdks/_source_control_configuration_client.py +++ /dev/null @@ -1,280 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from typing import TYPE_CHECKING - -from azure.mgmt.core import ARMPipelineClient -from azure.profiles import KnownProfiles, ProfileDefinition -from azure.profiles.multiapiclient import MultiApiClientMixin -from msrest import Deserializer, Serializer - -from ._configuration import SourceControlConfigurationClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -class _SDKClient(object): - def __init__(self, *args, **kwargs): - """This is a fake class to support current implemetation of MultiApiClientMixin." - Will be removed in final version of multiapi azure-core based client - """ - pass - -class SourceControlConfigurationClient(MultiApiClientMixin, _SDKClient): - """KubernetesConfiguration Client. - - This ready contains multiple API versions, to help you deal with all of the Azure clouds - (Azure Stack, Azure Government, Azure China, etc.). - By default, it uses the latest API version available on public Azure. - For production, you should stick to a particular api-version and/or profile. - The profile sets a mapping between an operation group and its API version. - The api-version parameter sets the default API version if the operation - group is not described in the profile. - - :param credential: Credential needed for the client to connect to Azure. - :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). - :type subscription_id: str - :param api_version: API version to use if no profile is provided, or if missing in profile. - :type api_version: str - :param base_url: Service URL - :type base_url: str - :param profile: A profile definition, from KnownProfiles to dict. - :type profile: azure.profiles.KnownProfiles - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - """ - - DEFAULT_API_VERSION = '2021-03-01' - _PROFILE_TAG = "azure.mgmt.kubernetesconfiguration.SourceControlConfigurationClient" - LATEST_PROFILE = ProfileDefinition({ - _PROFILE_TAG: { - None: DEFAULT_API_VERSION, - }}, - _PROFILE_TAG + " latest" - ) - - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - api_version=None, # type: Optional[str] - base_url=None, # type: Optional[str] - profile=KnownProfiles.default, # type: KnownProfiles - **kwargs # type: Any - ): - if not base_url: - base_url = 'https://management.azure.com' - self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - super(SourceControlConfigurationClient, self).__init__( - api_version=api_version, - profile=profile - ) - - @classmethod - def _models_dict(cls, api_version): - return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} - - @classmethod - def models(cls, api_version=DEFAULT_API_VERSION): - """Module depends on the API version: - - * 2020-07-01-preview: :mod:`v2020_07_01_preview.models` - * 2020-10-01-preview: :mod:`v2020_10_01_preview.models` - * 2021-03-01: :mod:`v2021_03_01.models` - * 2021-05-01-preview: :mod:`v2021_05_01_preview.models` - * 2021-06-01-preview: :mod:`v2021_06_01_preview.models` - """ - if api_version == '2020-07-01-preview': - from .v2020_07_01_preview import models - return models - elif api_version == '2020-10-01-preview': - from .v2020_10_01_preview import models - return models - elif api_version == '2021-03-01': - from .v2021_03_01 import models - return models - elif api_version == '2021-05-01-preview': - from .v2021_05_01_preview import models - return models - elif api_version == '2021-06-01-preview': - from .v2021_06_01_preview import models - return models - raise ValueError("API version {} is not available".format(api_version)) - - @property - def cluster_extension_type(self): - """Instance depends on the API version: - - * 2021-05-01-preview: :class:`ClusterExtensionTypeOperations` - """ - api_version = self._get_api_version('cluster_extension_type') - if api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import ClusterExtensionTypeOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'cluster_extension_type'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def cluster_extension_types(self): - """Instance depends on the API version: - - * 2021-05-01-preview: :class:`ClusterExtensionTypesOperations` - """ - api_version = self._get_api_version('cluster_extension_types') - if api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import ClusterExtensionTypesOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'cluster_extension_types'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def extension_type_versions(self): - """Instance depends on the API version: - - * 2021-05-01-preview: :class:`ExtensionTypeVersionsOperations` - """ - api_version = self._get_api_version('extension_type_versions') - if api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import ExtensionTypeVersionsOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'extension_type_versions'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def extensions(self): - """Instance depends on the API version: - - * 2020-07-01-preview: :class:`ExtensionsOperations` - * 2021-05-01-preview: :class:`ExtensionsOperations` - """ - api_version = self._get_api_version('extensions') - if api_version == '2020-07-01-preview': - from .v2020_07_01_preview.operations import ExtensionsOperations as OperationClass - elif api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import ExtensionsOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'extensions'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def flux_config_operation_status(self): - """Instance depends on the API version: - - * 2021-06-01-preview: :class:`FluxConfigOperationStatusOperations` - """ - api_version = self._get_api_version('flux_config_operation_status') - if api_version == '2021-06-01-preview': - from .v2021_06_01_preview.operations import FluxConfigOperationStatusOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'flux_config_operation_status'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def flux_configurations(self): - """Instance depends on the API version: - - * 2021-06-01-preview: :class:`FluxConfigurationsOperations` - """ - api_version = self._get_api_version('flux_configurations') - if api_version == '2021-06-01-preview': - from .v2021_06_01_preview.operations import FluxConfigurationsOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'flux_configurations'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def location_extension_types(self): - """Instance depends on the API version: - - * 2021-05-01-preview: :class:`LocationExtensionTypesOperations` - """ - api_version = self._get_api_version('location_extension_types') - if api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import LocationExtensionTypesOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'location_extension_types'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def operation_status(self): - """Instance depends on the API version: - - * 2021-05-01-preview: :class:`OperationStatusOperations` - * 2021-06-01-preview: :class:`OperationStatusOperations` - """ - api_version = self._get_api_version('operation_status') - if api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import OperationStatusOperations as OperationClass - elif api_version == '2021-06-01-preview': - from .v2021_06_01_preview.operations import OperationStatusOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'operation_status'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def operations(self): - """Instance depends on the API version: - - * 2020-07-01-preview: :class:`Operations` - * 2020-10-01-preview: :class:`Operations` - * 2021-03-01: :class:`Operations` - * 2021-05-01-preview: :class:`Operations` - * 2021-06-01-preview: :class:`Operations` - """ - api_version = self._get_api_version('operations') - if api_version == '2020-07-01-preview': - from .v2020_07_01_preview.operations import Operations as OperationClass - elif api_version == '2020-10-01-preview': - from .v2020_10_01_preview.operations import Operations as OperationClass - elif api_version == '2021-03-01': - from .v2021_03_01.operations import Operations as OperationClass - elif api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import Operations as OperationClass - elif api_version == '2021-06-01-preview': - from .v2021_06_01_preview.operations import Operations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - @property - def source_control_configurations(self): - """Instance depends on the API version: - - * 2020-07-01-preview: :class:`SourceControlConfigurationsOperations` - * 2020-10-01-preview: :class:`SourceControlConfigurationsOperations` - * 2021-03-01: :class:`SourceControlConfigurationsOperations` - * 2021-05-01-preview: :class:`SourceControlConfigurationsOperations` - """ - api_version = self._get_api_version('source_control_configurations') - if api_version == '2020-07-01-preview': - from .v2020_07_01_preview.operations import SourceControlConfigurationsOperations as OperationClass - elif api_version == '2020-10-01-preview': - from .v2020_10_01_preview.operations import SourceControlConfigurationsOperations as OperationClass - elif api_version == '2021-03-01': - from .v2021_03_01.operations import SourceControlConfigurationsOperations as OperationClass - elif api_version == '2021-05-01-preview': - from .v2021_05_01_preview.operations import SourceControlConfigurationsOperations as OperationClass - else: - raise ValueError("API version {} does not have operation group 'source_control_configurations'".format(api_version)) - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - - def close(self): - self._client.close() - def __enter__(self): - self._client.__enter__() - return self - def __exit__(self, *exc_details): - self._client.__exit__(*exc_details) diff --git a/src/k8s-config/setup.cfg b/src/k8s-config/setup.cfg deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/src/k8s-config/setup.py b/src/k8s-config/setup.py deleted file mode 100644 index 81a80330a8a..00000000000 --- a/src/k8s-config/setup.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/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. -# -------------------------------------------------------------------------------------------- - - -from codecs import open -from setuptools import setup, find_packages -try: - from azure_bdist_wheel import cmdclass -except ImportError: - from distutils import log as logger - logger.warn("Wheel is not available, disabling bdist_wheel hook") - -VERSION = '0.1.0' - -# The full list of classifiers is available at -# https://pypi.python.org/pypi?%3Aaction=list_classifiers -CLASSIFIERS = [ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'Intended Audience :: System Administrators', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'License :: OSI Approved :: MIT License', -] - -DEPENDENCIES = [ - "azure-cli-core", - "pycryptodome~=3.9.8" -] - -with open('README.rst', 'r', encoding='utf-8') as f: - README = f.read() -with open('HISTORY.rst', 'r', encoding='utf-8') as f: - HISTORY = f.read() - -setup( - name='k8s-config', - version=VERSION, - description='Microsoft Azure Command-Line Tools K8s-config Extension', - # TODO: Update author and email, if applicable - author='Microsoft Corporation', - author_email='azpycli@microsoft.com', - # TODO: consider pointing directly to your source code instead of the generic repo - url='https://github.com/Azure/azure-cli-extensions', - long_description=README + '\n\n' + HISTORY, - license='MIT', - classifiers=CLASSIFIERS, - packages=find_packages(), - install_requires=DEPENDENCIES, - package_data={'azext_k8s_config': ['azext_metadata.json']}, -) diff --git a/src/k8s-configuration/HISTORY.rst b/src/k8s-configuration/HISTORY.rst index 918019a6174..b8ef4668e03 100644 --- a/src/k8s-configuration/HISTORY.rst +++ b/src/k8s-configuration/HISTORY.rst @@ -3,6 +3,10 @@ Release History =============== +1.1.0 +++++++++++++++++++ +* Update sourceControlConfiguration resource models to Track2 + 1.0.1 ++++++++++++++++++ * Add provider registration check diff --git a/src/k8s-configuration/README.rst b/src/k8s-configuration/README.rst index 09ddc9d9bbb..a20cb951c98 100644 --- a/src/k8s-configuration/README.rst +++ b/src/k8s-configuration/README.rst @@ -15,7 +15,7 @@ az extension add --name k8s-configuration Kubernetes SourceControl Configuration: [more info](https://docs.microsoft.com/en-us/azure/kubernetessconfiguration/)\ *Examples:* -##### Create a KubernetesConfiguration +##### Create a Source Control Configuration (Fluxv1) ``` az k8s-configuration create \ --resource-group groupName \ @@ -31,7 +31,7 @@ az k8s-configuration create \ --helm-operator-params chartParameters ``` -##### Get a KubernetesConfiguration +##### Get a Source Control Configuration (Fluxv1) ``` az k8s-configuration show \ --resource-group groupName \ @@ -40,7 +40,7 @@ az k8s-configuration show \ --name configurationName ``` -##### Delete a KubernetesConfiguration +##### Delete a Source Control Configuration (Fluxv1) ``` az k8s-configuration delete \ --resource-group groupName \ @@ -49,7 +49,7 @@ az k8s-configuration delete \ --name configurationName ``` -##### Update a KubernetesConfiguration +##### Update a Source Control Configuration (Fluxv1) ``` az k8s-configuration create \ --resource-group groupName \ @@ -63,7 +63,7 @@ az k8s-configuration create \ --helm-operator-params chartParameters ``` -##### List all KubernetesConfigurations of a cluster +##### List all Source Control Configuration (Fluxv1) on a cluster ``` az k8s-configuration list \ --resource-group groupName \ diff --git a/src/k8s-configuration/azext_k8s_configuration/__init__.py b/src/k8s-configuration/azext_k8s_configuration/__init__.py index db560042e65..0b1445eba86 100644 --- a/src/k8s-configuration/azext_k8s_configuration/__init__.py +++ b/src/k8s-configuration/azext_k8s_configuration/__init__.py @@ -8,16 +8,16 @@ from azext_k8s_configuration._help import helps # pylint: disable=unused-import -class K8sConfigurationCommandsLoader(AzCommandsLoader): +class k8s_configCommandsLoader(AzCommandsLoader): def __init__(self, cli_ctx=None): from azure.cli.core.commands import CliCommandType - from azext_k8s_configuration._client_factory import cf_k8s_configuration - k8s_configuration_custom = CliCommandType( + from azext_k8s_configuration._client_factory import k8s_configuration_client + k8s_config_custom = CliCommandType( operations_tmpl='azext_k8s_configuration.custom#{}', - client_factory=cf_k8s_configuration) - super(K8sConfigurationCommandsLoader, self).__init__(cli_ctx=cli_ctx, - custom_command_type=k8s_configuration_custom) + client_factory=k8s_configuration_client) + super().__init__(cli_ctx=cli_ctx, + custom_command_type=k8s_config_custom) def load_command_table(self, args): from azext_k8s_configuration.commands import load_command_table @@ -29,4 +29,4 @@ def load_arguments(self, command): load_arguments(self, command) -COMMAND_LOADER_CLS = K8sConfigurationCommandsLoader +COMMAND_LOADER_CLS = k8s_configCommandsLoader diff --git a/src/k8s-configuration/azext_k8s_configuration/_client_factory.py b/src/k8s-configuration/azext_k8s_configuration/_client_factory.py index 86cbd33b7f4..bea14dcebfa 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_client_factory.py +++ b/src/k8s-configuration/azext_k8s_configuration/_client_factory.py @@ -4,17 +4,42 @@ # -------------------------------------------------------------------------------------------- from azure.cli.core.commands.client_factory import get_mgmt_service_client +from azure.cli.core.profiles import ResourceType +from . import consts -def cf_k8s_configuration(cli_ctx, *_): +def k8s_configuration_client(cli_ctx, **kwargs): from azext_k8s_configuration.vendored_sdks import SourceControlConfigurationClient - return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient) + return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient, **kwargs) -def cf_k8s_configuration_operation(cli_ctx, _): - return cf_k8s_configuration(cli_ctx).source_control_configurations +def k8s_configuration_fluxconfig_client(cli_ctx, *_): + return k8s_configuration_client(cli_ctx, api_version=consts.FLUXCONFIG_API_VERSION).flux_configurations -def _resource_providers_client(cli_ctx): +def k8s_configuration_sourcecontrol_client(cli_ctx, *_): + return k8s_configuration_client(cli_ctx, api_version=consts.SOURCE_CONTROL_API_VERSION).source_control_configurations + + +def k8s_configuration_extension_client(cli_ctx, *_): + return k8s_configuration_client(cli_ctx, api_version=consts.EXTENSION_API_VERSION).extensions + + +def resource_providers_client(cli_ctx): from azure.mgmt.resource import ResourceManagementClient return get_mgmt_service_client(cli_ctx, ResourceManagementClient).providers + + +def cf_resource_groups(cli_ctx, subscription_id=None): + return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, + subscription_id=subscription_id).resource_groups + + +def cf_resources(cli_ctx, subscription_id=None): + return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, + subscription_id=subscription_id).resources + + +def cf_log_analytics(cli_ctx, subscription_id=None): + from azure.mgmt.loganalytics import LogAnalyticsManagementClient # pylint: disable=no-name-in-module + return get_mgmt_service_client(cli_ctx, LogAnalyticsManagementClient, subscription_id=subscription_id) diff --git a/src/k8s-configuration/azext_k8s_configuration/_consts.py b/src/k8s-configuration/azext_k8s_configuration/_consts.py deleted file mode 100644 index e58470e7e78..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/_consts.py +++ /dev/null @@ -1,7 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -PROVIDER_NAMESPACE = 'Microsoft.KubernetesConfiguration' -REGISTERED = "Registered" diff --git a/src/k8s-configuration/azext_k8s_configuration/_format.py b/src/k8s-configuration/azext_k8s_configuration/_format.py deleted file mode 100644 index a1ea04822d8..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/_format.py +++ /dev/null @@ -1,25 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from collections import OrderedDict - - -def k8s_configuration_list_table_format(results): - return [__get_table_row(result) for result in results] - - -def k8s_configuration_show_table_format(result): - return __get_table_row(result) - - -def __get_table_row(result): - return OrderedDict([ - ('name', result['name']), - ('repositoryUrl', result['repositoryUrl']), - ('operatorName', result['operatorInstanceName']), - ('operatorNamespace', result['operatorNamespace']), - ('scope', result['operatorScope']), - ('provisioningState', result['provisioningState']) - ]) diff --git a/src/k8s-configuration/azext_k8s_configuration/_help.py b/src/k8s-configuration/azext_k8s_configuration/_help.py index 3fa338c7b28..e3c5ec1d50d 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_help.py +++ b/src/k8s-configuration/azext_k8s_configuration/_help.py @@ -6,10 +6,9 @@ from knack.help_files import helps # pylint: disable=unused-import - helps['k8s-configuration'] = """ type: group - short-summary: Commands to manage Kubernetes configuration. + short-summary: Commands to manage resources from Microsoft.KubernetesConfiguration. """ helps['k8s-configuration create'] = """ @@ -57,14 +56,96 @@ --cluster-type connectedClusters --name MyConfigurationName """ -helps['k8s-configuration update'] = """ +helps['k8s-configuration flux'] = """ + type: group + short-summary: Commands to manage Flux V2 Kubernetes configurations. +""" + +helps['k8s-configuration flux create'] = """ + type: command + short-summary: Create a Kubernetes Flux Configuration. + examples: + - name: Create a Kubernetes Flux Configuration + text: |- + az k8s-configuration flux create --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ + --kind git --url https://github.com/Azure/arc-k8s-demo --branch master --kustomization \\ + name=my-kustomization +""" + +helps['k8s-configuration flux list'] = """ + type: command + short-summary: List Kubernetes Flux Configurations. + examples: + - name: List all Kubernetes Flux Configurations on a cluster + text: |- + az k8s-configuration flux list --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters +""" + +helps['k8s-configuration flux show'] = """ + type: command + short-summary: Show a Kubernetes Flux Configuration. + examples: + - name: Show details of a Kubernetes Flux Configuration + text: |- + az k8s-configuration flux show --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myconfig +""" + +helps['k8s-configuration flux delete'] = """ + type: command + short-summary: Delete a Kubernetes Flux Configuration. + examples: + - name: Delete an existing Kubernetes Flux Configuration + text: |- + az k8s-configuration flux delete --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myconfig +""" + +helps['k8s-config extension'] = """ + type: group + short-summary: Commands to manage Kubernetes Extensions. +""" + +helps['k8s-config extension create'] = """ + type: command + short-summary: Create a Kubernetes Extension. + examples: + - name: Create a Kubernetes Extension + text: |- + az k8s-config extension create --resource-group my-resource-group \\ + --cluster-name mycluster --cluster-type connectedClusters \\ + --name myextension --extension-type microsoft.openservicemesh \\ + --scope cluster --release-train stable +""" + +helps['k8s-config extension list'] = """ + type: command + short-summary: List Kubernetes Extensions. + examples: + - name: List all Kubernetes Extensions on a cluster + text: |- + az k8s-config extension list --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters +""" + +helps['k8s-config extension show'] = """ + type: command + short-summary: Show a Kubernetes Extension. + examples: + - name: Show details of a Kubernetes Extension + text: |- + az k8s-config extension show --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myextension +""" + +helps['k8s-config extension delete'] = """ type: command - short-summary: Update a Kubernetes configuration. + short-summary: Delete a Kubernetes Extension. examples: - - name: Update an existing Kubernetes configuration + - name: Delete an existing Kubernetes Extension text: |- - az k8s-configuration update --resource-group MyResourceGroup --cluster-name MyClusterName \\ - --cluster-type connectedClusters --name MyConfigurationName --enable-helm-operator \\ - --repository-url git://github.com/fluxHowTo/flux-get-started --operator-params "'--git-readonly'" \\ - --helm-operator-chart-version 1.2.0 --helm-operator-params '--set helm.versions=v3' + az k8s-config extension delete --resource-group my-resource-group --cluster-name mycluster \\ + --cluster-type connectedClusters --name myextension """ diff --git a/src/k8s-configuration/azext_k8s_configuration/_params.py b/src/k8s-configuration/azext_k8s_configuration/_params.py index c9faab38cfb..55e23eab241 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_params.py +++ b/src/k8s-configuration/azext_k8s_configuration/_params.py @@ -3,44 +3,124 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long +# pylint: disable=too-many-statements -from knack.arguments import CLIArgumentType - +from azure.cli.core.commands.validators import get_default_location_from_resource_group from azure.cli.core.commands.parameters import ( - get_three_state_flag, get_enum_type, + get_three_state_flag, tags_type ) +from .validators import ( + validate_configuration_name, + validate_fluxconfig_name, + validate_namespace, + validate_operator_instance_name, + validate_operator_namespace +) -from azure.cli.core.commands.validators import get_default_location_from_resource_group -from ._validators import _validate_configuration_type, _validate_operator_namespace, _validate_operator_instance_name +from .action import ( + KustomizationAddAction, +) +from . import consts def load_arguments(self, _): - sourcecontrolconfiguration_type = CLIArgumentType(help='Name of the Kubernetes Configuration') - with self.argument_context('k8s-configuration') as c: c.argument('tags', tags_type) - c.argument('location', - validator=get_default_location_from_resource_group) - c.argument('name', sourcecontrolconfiguration_type, - options_list=['--name', '-n']) + c.argument('location', validator=get_default_location_from_resource_group) c.argument('cluster_name', options_list=['--cluster-name', '-c'], help='Name of the Kubernetes cluster') c.argument('cluster_type', + options_list=['--cluster-type', '-t'], arg_type=get_enum_type(['connectedClusters', 'managedClusters']), - help='Specify Arc clusters or AKS managed clusters.') + help='Specify Arc connected clusters or AKS managed clusters.') + + with self.argument_context('k8s-configuration flux') as c: + c.argument('name', + options_list=['--name', '-n'], + help='Name of the flux configuration', + validator=validate_fluxconfig_name) + + with self.argument_context('k8s-configuration flux create') as c: + c.argument('scope', + options_list=['--scope', '-s'], + arg_type=get_enum_type(['namespace', 'cluster']), + help="Specify scope of the operator to be 'namespace' or 'cluster'") + c.argument('namespace', + help='Namespace to deploy the configuration', + options_list=['--namespace', '--ns'], + validator=validate_namespace) + c.argument('kind', + arg_type=get_enum_type([consts.GIT]), + help='Source kind to reconcile') + c.argument('url', + options_list=['--url', '-u'], + help='URL of the git repo source to reconcile') + c.argument('timeout', + help='Maximum time to reconcile the source before timing out') + c.argument('sync_interval', + options_list=['--interval', '--sync-interval'], + help='Time between reconciliations of the source on the cluster') + c.argument('branch', + arg_group="Git Repo Ref", + help='Branch within the git source to reconcile with the cluster') + c.argument('tag', + arg_group="Git Repo Ref", + help='Tag within the git source to reconcile with the cluster') + c.argument('semver', + arg_group="Git Repo Ref", + help='Semver range within the git source to reconcile with the cluster') + c.argument('commit', + arg_group="Git Repo Ref", + help='Commit within the git source to reconcile with the cluster') + c.argument('ssh_private_key', + arg_group="Auth", + help='Base64-encoded private ssh key for private repository sync') + c.argument('ssh_private_key_file', + arg_group="Auth", + help='Filepath to private ssh key for private repository sync') + c.argument('https_user', + arg_group="Auth", + help='HTTPS username for private repository sync') + c.argument('https_key', + arg_group="Auth", + help='HTTPS token/password for private repository sync') + c.argument('known_hosts', + arg_group="Auth", + help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') + c.argument('known_hosts_file', + arg_group="Auth", + help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') + c.argument('local_auth_ref', + options_list=['--local-auth-ref', '--local-ref'], + arg_group="Auth", + help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') + c.argument('suspend', + help='Suspend the reconciliation of the source and kustomizations associated with this configuration') + c.argument('kustomization', + action=KustomizationAddAction, + help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", + nargs='+') + + with self.argument_context('k8s-configuration flux delete') as c: + c.argument('force', + help='Specify whether to force delete the flux configuration from the cluster.') + + with self.argument_context('k8s-configuration') as c: + c.argument('name', + options_list=['--name', '-n'], + help='Name of the configuration', + validator=validate_configuration_name) + + with self.argument_context('k8s-configuration create') as c: c.argument('repository_url', options_list=['--repository-url', '-u'], help='Url of the source control repository') c.argument('scope', arg_type=get_enum_type(['namespace', 'cluster']), help='''Specify scope of the operator to be 'namespace' or 'cluster' ''') - c.argument('configuration_type', - validator=_validate_configuration_type, - arg_type=get_enum_type(['sourceControlConfiguration']), - help='Type of the configuration') c.argument('enable_helm_operator', arg_group="Helm Operator", arg_type=get_three_state_flag(), @@ -60,11 +140,11 @@ def load_arguments(self, _): c.argument('operator_instance_name', arg_group="Operator", help='Instance name of the Operator', - validator=_validate_operator_instance_name) + validator=validate_operator_instance_name) c.argument('operator_namespace', arg_group="Operator", help='Namespace in which to install the Operator', - validator=_validate_operator_namespace) + validator=validate_operator_namespace) c.argument('operator_type', arg_group="Operator", help='''Type of the operator. Valid value is 'flux' ''') @@ -86,3 +166,81 @@ def load_arguments(self, _): c.argument('ssh_known_hosts_file', arg_group="Auth", help='Specify filepath to known_hosts contents containing public SSH keys required to access private Git instances') + + # with self.argument_context('k8s-config flux source') as c: + # c.argument('scope', + # options_list=['--scope', '-s'], + # arg_type=get_enum_type(['namespace', 'cluster']), + # help="Specify scope of the operator to be 'namespace' or 'cluster'") + # c.argument('namespace', + # help='Namespace to deploy the configuration', + # options_list=['--namespace', '--ns'], + # validator=validate_namespace) + # c.argument('kind', + # arg_type=get_enum_type([consts.GIT]), + # help='Source kind to reconcile') + # c.argument('url', + # options_list=['--url', '-u'], + # help='URL of the source to reconcile') + # c.argument('timeout', + # help='Maximum time to reconcile the source before timing out') + # c.argument('sync_interval', + # options_list=['--interval', '--sync-interval'], + # help='Time between reconciliations of the source on the cluster') + # c.argument('branch', + # arg_group="Repo Ref", + # help='Branch to reconcile with the git source') + # c.argument('tag', + # arg_group="Repo Ref", + # help='Tag to reconcile with the git source') + # c.argument('semver', + # arg_group="Repo Ref", + # help='Semver range to reconcile with the git source') + # c.argument('commit', + # arg_group="Repo Ref", + # help='Specific commit to reconcile with the git source') + # c.argument('ssh_private_key', + # arg_group="Auth", + # help='Base64-encoded private ssh key for private repository sync') + # c.argument('ssh_private_key_file', + # arg_group="Auth", + # help='Filepath to private ssh key for private repository sync') + # c.argument('https_user', + # arg_group="Auth", + # help='HTTPS username for private repository sync') + # c.argument('https_key', + # arg_group="Auth", + # help='HTTPS token/password for private repository sync') + # c.argument('known_hosts', + # arg_group="Auth", + # help='Base64-encoded known_hosts data containing public SSH keys required to access private Git instances') + # c.argument('known_hosts_file', + # arg_group="Auth", + # help='Filepath to known_hosts contents containing public SSH keys required to access private Git instances') + # c.argument('local_auth_ref', + # options_list=['--local-auth-ref'], + # arg_group="Auth", + # help='Local reference to a kubernetes secret in the configuration namespace to use for communication to the source') + + # with self.argument_context('k8s-config flux kustomization') as c: + # c.argument('kustomization_name', + # help='Specify the name of the kustomization to add to the configuration') + # c.argument('path', + # help='Specify the path in the source that the kustomization should apply') + # c.argument('dependencies', + # options_list=['--depends', '--dependencies'], + # help='Specify the names of kustomization dependencies') + # c.argument('timeout', + # help='Maximum time to reconcile the kustomization before timing out') + # c.argument('sync_interval', + # options_list=['--interval', '--sync-interval'], + # help='Time between reconciliations of the kustomization on the cluster') + # c.argument('retry_interval', + # help='Time between reconciliations of the kustomization on the cluster on failures, defaults to --sync-interval') + # c.argument('prune', + # help='Whether to garbage collect resources deployed by the kustomization on the cluster') + # c.argument('force', + # help='Whether to re-create resources that cannot be updated on the cluster (i.e. jobs)') + # c.argument('validation', + # arg_type=get_enum_type(['none', 'client', 'server']), + # help='Specify whether to dry-run manifests at the client or at the apiserver level before applying them to the cluster.') diff --git a/src/k8s-configuration/azext_k8s_configuration/_utils.py b/src/k8s-configuration/azext_k8s_configuration/_utils.py deleted file mode 100644 index 6ad8e600636..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/_utils.py +++ /dev/null @@ -1,61 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -import base64 -from azure.cli.core.azclierror import MutuallyExclusiveArgumentError, InvalidArgumentValueError - - -def _get_cluster_type(cluster_type): - if cluster_type.lower() == 'connectedclusters': - return 'Microsoft.Kubernetes' - # Since cluster_type is an enum of only two values, if not connectedClusters, it will be managedClusters. - return 'Microsoft.ContainerService' - - -def _fix_compliance_state(config): - # If we get Compliant/NonCompliant as compliance_sate, change them before returning - if config.compliance_status.compliance_state.lower() == 'noncompliant': - config.compliance_status.compliance_state = 'Failed' - elif config.compliance_status.compliance_state.lower() == 'compliant': - config.compliance_status.compliance_state = 'Installed' - - return config - - -def _get_data_from_key_or_file(key, filepath): - if key != '' and filepath != '': - raise MutuallyExclusiveArgumentError( - 'Error! Both textual key and key filepath cannot be provided', - 'Try providing the file parameter without providing the plaintext parameter') - data = '' - if filepath != '': - data = _read_key_file(filepath) - elif key != '': - data = key - return data - - -def _read_key_file(path): - try: - with open(path, "r") as myfile: # user passed in filename - data_list = myfile.readlines() # keeps newline characters intact - data_list_len = len(data_list) - if (data_list_len) <= 0: - raise Exception("File provided does not contain any data") - raw_data = ''.join(data_list) - return _to_base64(raw_data) - except Exception as ex: - raise InvalidArgumentValueError( - 'Error! Unable to read key file specified with: {0}'.format(ex), - 'Verify that the filepath specified exists and contains valid utf-8 data') from ex - - -def _from_base64(base64_str): - return base64.b64decode(base64_str) - - -def _to_base64(raw_data): - bytes_data = raw_data.encode('utf-8') - return base64.b64encode(bytes_data).decode('utf-8') diff --git a/src/k8s-configuration/azext_k8s_configuration/_validators.py b/src/k8s-configuration/azext_k8s_configuration/_validators.py deleted file mode 100644 index 47c6b97ca3a..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/_validators.py +++ /dev/null @@ -1,143 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# 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 io -from azure.cli.core.azclierror import InvalidArgumentValueError, MutuallyExclusiveArgumentError - -from knack.log import get_logger -from azext_k8s_configuration._client_factory import _resource_providers_client -from azext_k8s_configuration._utils import _from_base64 -import azext_k8s_configuration._consts as consts -from urllib.parse import urlparse -from paramiko.hostkeys import HostKeyEntry -from paramiko.ed25519key import Ed25519Key -from paramiko.ssh_exception import SSHException -from Crypto.PublicKey import RSA, ECC, DSA - - -logger = get_logger(__name__) - - -# Parameter-Level Validation -def _validate_configuration_type(configuration_type): - if configuration_type.lower() != 'sourcecontrolconfiguration': - raise InvalidArgumentValueError( - 'Invalid configuration-type', - 'Try specifying the valid value "sourceControlConfiguration"') - - -def _validate_operator_namespace(namespace): - if namespace.operator_namespace: - _validate_k8s_name(namespace.operator_namespace, "--operator-namespace", 23) - - -def _validate_operator_instance_name(namespace): - if namespace.operator_instance_name: - _validate_k8s_name(namespace.operator_instance_name, "--operator-instance-name", 23) - - -# Create Parameter Validation -def _validate_configuration_name(configuration_name): - _validate_k8s_name(configuration_name, "--name", 63) - - -# Helper -def _validate_k8s_name(param_value, param_name, max_len): - if len(param_value) > max_len: - raise InvalidArgumentValueError( - 'Error! Invalid {0}'.format(param_name), - 'Parameter {0} can be a maximum of {1} characters'.format(param_name, max_len)) - if not re.match(r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?$', param_value): - if param_value[0] == "-" or param_value[-1] == "-": - raise InvalidArgumentValueError( - 'Error! Invalid {0}'.format(param_name), - 'Parameter {0} cannot begin or end with a hyphen'.format(param_name)) - raise InvalidArgumentValueError( - 'Error! Invalid {0}'.format(param_name), - 'Parameter {0} can only contain lowercase alphanumeric characters and hyphens'.format(param_name)) - - -def _validate_url_with_params(repository_url, ssh_private_key_set, known_hosts_contents_set, https_auth_set): - scheme = urlparse(repository_url).scheme - - if scheme.lower() in ('http', 'https'): - if ssh_private_key_set: - raise MutuallyExclusiveArgumentError( - 'Error! An --ssh-private-key cannot be used with an http(s) url', - 'Verify the url provided is a valid ssh url and not an http(s) url') - if known_hosts_contents_set: - raise MutuallyExclusiveArgumentError( - 'Error! --ssh-known-hosts cannot be used with an http(s) url', - 'Verify the url provided is a valid ssh url and not an http(s) url') - if not https_auth_set and scheme == 'https': - logger.warning('Warning! https url is being used without https auth params, ensure the repository ' - 'url provided is not a private repo') - else: - if https_auth_set: - raise MutuallyExclusiveArgumentError( - 'Error! https auth (--https-user and --https-key) cannot be used with a non-http(s) url', - 'Verify the url provided is a valid http(s) url and not an ssh url') - - -def _validate_known_hosts(knownhost_data): - try: - knownhost_str = _from_base64(knownhost_data).decode('utf-8') - except Exception as ex: - raise InvalidArgumentValueError( - 'Error! ssh known_hosts is not a valid utf-8 base64 encoded string', - 'Verify that the string provided safely decodes into a valid utf-8 format') from ex - lines = knownhost_str.split('\n') - for line in lines: - line = line.strip(' ') - line_len = len(line) - if (line_len == 0) or (line[0] == "#"): - continue - try: - host_key = HostKeyEntry.from_line(line) - if not host_key: - raise Exception('not enough fields found in known_hosts line') - except Exception as ex: - raise InvalidArgumentValueError( - 'Error! ssh known_hosts provided in wrong format', - 'Verify that all lines in the known_hosts contents are provided in a valid sshd(8) format') from ex - - -def _validate_private_key(ssh_private_key_data): - try: - RSA.import_key(_from_base64(ssh_private_key_data)) - return - except ValueError: - try: - ECC.import_key(_from_base64(ssh_private_key_data)) - return - except ValueError: - try: - DSA.import_key(_from_base64(ssh_private_key_data)) - return - except ValueError: - try: - key_obj = io.StringIO(_from_base64(ssh_private_key_data).decode('utf-8')) - Ed25519Key(file_obj=key_obj) - return - except SSHException: - raise InvalidArgumentValueError( - 'Error! --ssh-private-key provided in invalid format', - 'Verify the key provided is a valid PEM-formatted key of type RSA, ECC, DSA, or Ed25519') - - -# pylint: disable=broad-except -def _validate_cc_registration(cmd): - try: - rp_client = _resource_providers_client(cmd.cli_ctx) - registration_state = rp_client.get(consts.PROVIDER_NAMESPACE).registration_state - - if registration_state.lower() != consts.REGISTERED.lower(): - logger.warning("'Source Control Configuration' cannot be used because '%s' provider has not been " - "registered. More details for registering this provider can be found here - " - "https://aka.ms/RegisterKubernetesConfigurationProvider", consts.PROVIDER_NAMESPACE) - except Exception: - logger.warning("Unable to fetch registration state of '%s' provider. " - "Failed to enable 'source control configuration' feature...", consts.PROVIDER_NAMESPACE) diff --git a/src/k8s-config/azext_k8s_config/action.py b/src/k8s-configuration/azext_k8s_configuration/action.py similarity index 100% rename from src/k8s-config/azext_k8s_config/action.py rename to src/k8s-configuration/azext_k8s_configuration/action.py diff --git a/src/k8s-configuration/azext_k8s_configuration/commands.py b/src/k8s-configuration/azext_k8s_configuration/commands.py index 541dfe3943b..67c42428ed7 100644 --- a/src/k8s-configuration/azext_k8s_configuration/commands.py +++ b/src/k8s-configuration/azext_k8s_configuration/commands.py @@ -5,19 +5,39 @@ # pylint: disable=line-too-long from azure.cli.core.commands import CliCommandType -from azext_k8s_configuration._client_factory import (cf_k8s_configuration, cf_k8s_configuration_operation) -from ._format import k8s_configuration_show_table_format, k8s_configuration_list_table_format +from azext_k8s_configuration._client_factory import ( + k8s_configuration_fluxconfig_client, + k8s_configuration_sourcecontrol_client +) +from .format import ( + fluxconfig_list_table_format, + fluxconfig_show_table_format, + sourcecontrol_list_table_format, + sourcecontrol_show_table_format +) def load_command_table(self, _): + k8s_configuration_fluxconfig_sdk = CliCommandType( + operations_tmpl='azext_k8s_configuration.vendored_sdks.operations#FluxConfigurationsOperations.{}', + client_factory=k8s_configuration_fluxconfig_client + ) - k8s_configuration_sdk = CliCommandType( + k8s_configuration_sourcecontrol_sdk = CliCommandType( operations_tmpl='azext_k8s_configuration.vendored_sdks.operations#SourceControlConfigurationsOperations.{}', - client_factory=cf_k8s_configuration) + client_factory=k8s_configuration_sourcecontrol_client + ) - with self.command_group('k8s-configuration', k8s_configuration_sdk, client_factory=cf_k8s_configuration_operation) as g: - g.custom_command('create', 'create_k8s_configuration') - g.custom_command('update', 'update_k8s_configuration') - g.custom_command('delete', 'delete_k8s_configuration', confirmation=True) - g.custom_command('list', 'list_k8s_configuration', table_transformer=k8s_configuration_list_table_format) - g.custom_show_command('show', 'show_k8s_configuration', table_transformer=k8s_configuration_show_table_format) + with self.command_group('k8s-configuration flux', k8s_configuration_fluxconfig_sdk, client_factory=k8s_configuration_fluxconfig_sdk, is_experimental=True) as g: + g.custom_command('create', 'flux_config_create', supports_no_wait=True) + g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) + g.custom_show_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) + g.custom_command('delete', 'flux_config_delete', confirmation=True, supports_no_wait=True) + # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) + # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) + + with self.command_group('k8s-configuration', k8s_configuration_sourcecontrol_sdk, client_factory=k8s_configuration_sourcecontrol_sdk) as g: + g.custom_command('create', 'sourcecontrol_create', deprecate_info=self.deprecate(redirect='k8s-configuration flux create')) + g.custom_command('list', 'sourcecontrol_list', table_transformer=sourcecontrol_list_table_format, deprecate_info=self.deprecate(redirect='k8s-configuration flux list')) + g.custom_show_command('show', 'sourcecontrol_show', table_transformer=sourcecontrol_show_table_format, deprecate_info=self.deprecate(redirect='k8s-configuration flux show')) + g.custom_command('delete', 'sourcecontrol_delete', confirmation=True, deprecate_info=self.deprecate(redirect='k8s-configuration flux delete')) diff --git a/src/k8s-config/azext_k8s_config/confirm.py b/src/k8s-configuration/azext_k8s_configuration/confirm.py similarity index 100% rename from src/k8s-config/azext_k8s_config/confirm.py rename to src/k8s-configuration/azext_k8s_configuration/confirm.py diff --git a/src/k8s-config/azext_k8s_config/consts.py b/src/k8s-configuration/azext_k8s_configuration/consts.py similarity index 100% rename from src/k8s-config/azext_k8s_config/consts.py rename to src/k8s-configuration/azext_k8s_configuration/consts.py diff --git a/src/k8s-configuration/azext_k8s_configuration/custom.py b/src/k8s-configuration/azext_k8s_configuration/custom.py index 8882fd16cff..181ce707b5f 100644 --- a/src/k8s-configuration/azext_k8s_configuration/custom.py +++ b/src/k8s-configuration/azext_k8s_configuration/custom.py @@ -3,227 +3,121 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from azure.cli.core.azclierror import ResourceNotFoundError, CommandNotFoundError, \ - RequiredArgumentMissingError -from knack.log import get_logger -from azext_k8s_configuration._utils import _get_cluster_type, \ - _fix_compliance_state, _get_data_from_key_or_file, _to_base64 -from azext_k8s_configuration._validators import _validate_known_hosts, _validate_url_with_params, \ - _validate_configuration_name, _validate_cc_registration, _validate_private_key - -from azext_k8s_configuration.vendored_sdks.models import SourceControlConfiguration -from azext_k8s_configuration.vendored_sdks.models import HelmOperatorProperties -from azext_k8s_configuration.vendored_sdks.models import ErrorResponseException - -logger = get_logger(__name__) - - -def show_k8s_configuration(client, resource_group_name, cluster_name, name, cluster_type): - """Get an existing Kubernetes Source Control Configuration. - - """ - # Determine ClusterRP - cluster_rp = _get_cluster_type(cluster_type) - - try: - config = client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name) - return _fix_compliance_state(config) - except ErrorResponseException as ex: - # Customize the error message for resources not found - if ex.response.status_code == 404: - # If Cluster not found - if ex.message.__contains__("(ResourceNotFound)"): - message = ex.message - recommendation = 'Verify that the --cluster-type is correct and the Resource ' \ - '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name) - # If Configuration not found - elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): - message = '(ConfigurationNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/' \ - 'sourcecontrolConfigurations/{3} could not be found!'.format(cluster_rp, cluster_type, - cluster_name, name) - recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \ - '/sourcecontrolConfigurations/{3} exists'.format(cluster_rp, cluster_type, - cluster_name, name) - else: - message = ex.message - recommendation = '' - raise ResourceNotFoundError(message, recommendation) from ex +# pylint: disable=unused-argument + +from .providers.ExtensionProvider import ExtensionProvider +from .providers.FluxConfigurationProvider import FluxConfigurationProvider +from .providers.SourceControlConfigurationProvider import SourceControlConfigurationProvider +from . import consts + + +# Source Control Configuration Methods + +def sourcecontrol_create(cmd, client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, + operator_instance_name=None, operator_namespace='default', + helm_operator_chart_version='1.2.0', operator_type='flux', operator_params='', + ssh_private_key='', ssh_private_key_file='', https_user='', https_key='', + ssh_known_hosts='', ssh_known_hosts_file='', enable_helm_operator=None, + helm_operator_params=''): + provider = SourceControlConfigurationProvider(cmd) + return provider.create(resource_group_name, cluster_name, name, repository_url, scope, cluster_type, + operator_instance_name, operator_namespace, helm_operator_chart_version, operator_type, + operator_params, ssh_private_key, ssh_private_key_file, https_user, https_key, + ssh_known_hosts, ssh_known_hosts_file, enable_helm_operator, helm_operator_params) + +def sourcecontrol_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = SourceControlConfigurationProvider(cmd) + return provider.show(resource_group_name, cluster_type, cluster_name, name) + + +def sourcecontrol_list(cmd, client, resource_group_name, cluster_type, cluster_name): + provider = SourceControlConfigurationProvider(cmd) + return provider.list(resource_group_name, cluster_type, cluster_name) + + +def sourcecontrol_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = SourceControlConfigurationProvider(cmd) + return provider.delete(resource_group_name, cluster_type, cluster_name, name) + + +# Flux Configuration Methods + +def flux_config_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = FluxConfigurationProvider(cmd) + return provider.show(resource_group_name, cluster_type, cluster_name, name) + + +def flux_config_list(cmd, client, resource_group_name, cluster_type, cluster_name): + provider = FluxConfigurationProvider(cmd) + return provider.list(resource_group_name, cluster_type, cluster_name) # pylint: disable=too-many-locals -def create_k8s_configuration(cmd, client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, - operator_instance_name=None, operator_namespace='default', - helm_operator_chart_version='1.2.0', operator_type='flux', operator_params='', - ssh_private_key='', ssh_private_key_file='', https_user='', https_key='', - ssh_known_hosts='', ssh_known_hosts_file='', enable_helm_operator=None, - helm_operator_params=''): - """Create a new Kubernetes Source Control Configuration. - - """ - # Validate configuration name - _validate_configuration_name(name) - - # Determine ClusterRP - cluster_rp = _get_cluster_type(cluster_type) - - # Determine operatorInstanceName - if operator_instance_name is None: - operator_instance_name = name - - # Create helmOperatorProperties object - helm_operator_properties = None - if enable_helm_operator: - helm_operator_properties = HelmOperatorProperties() - helm_operator_properties.chart_version = helm_operator_chart_version.strip() - helm_operator_properties.chart_values = helm_operator_params.strip() - - protected_settings = _get_protected_settings(ssh_private_key, - ssh_private_key_file, - https_user, - https_key) - knownhost_data = _get_data_from_key_or_file(ssh_known_hosts, ssh_known_hosts_file) - if knownhost_data: - _validate_known_hosts(knownhost_data) - - # Flag which parameters have been set and validate these settings against the set repository url - ssh_private_key_set = ssh_private_key != '' or ssh_private_key_file != '' - known_hosts_contents_set = knownhost_data != '' - https_auth_set = https_user != '' and https_key != '' - _validate_url_with_params(repository_url, - ssh_private_key_set=ssh_private_key_set, - known_hosts_contents_set=known_hosts_contents_set, - https_auth_set=https_auth_set) - - # Validate that the subscription is registered to Microsoft.KubernetesConfiguration - _validate_cc_registration(cmd) - - # Create sourceControlConfiguration object - source_control_configuration = SourceControlConfiguration(repository_url=repository_url, - operator_namespace=operator_namespace, - operator_instance_name=operator_instance_name, - operator_type=operator_type, - operator_params=operator_params, - configuration_protected_settings=protected_settings, - operator_scope=scope, - ssh_known_hosts_contents=knownhost_data, - enable_helm_operator=enable_helm_operator, - helm_operator_properties=helm_operator_properties) - - # Try to create the resource - config = client.create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, - name, source_control_configuration) - - return _fix_compliance_state(config) - - -def update_k8s_configuration(client, resource_group_name, cluster_name, name, cluster_type, - repository_url=None, operator_params=None, ssh_known_hosts='', - ssh_known_hosts_file='', enable_helm_operator=None, helm_operator_chart_version=None, - helm_operator_params=None): - """Update an existing Kubernetes Source Control Configuration. - - """ - - # TODO: Remove this after we eventually get PATCH implemented for update and uncomment - raise CommandNotFoundError( - "\"k8s-configuration update\" currently is not available. " - "Use \"k8s-configuration create\" to update a previously created configuration." - ) - - # # Determine ClusterRP - # cluster_rp = __get_cluster_type(cluster_type) - - # source_control_configuration_name = name.strip() - - # config = client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, - # source_control_configuration_name) - # update_yes = False - - # # Set input values, if they are supplied - # if repository_url is not None: - # config.repository_url = repository_url - # update_yes = True - - # if operator_params is not None: - # config.operator_params = operator_params - # update_yes = True - - # knownhost_data = get_data_from_key_or_file(ssh_known_hosts, ssh_known_hosts_file) - # if knownhost_data: - # validate_known_hosts(knownhost_data) - # config.ssh_known_hosts_contents = knownhost_data - # update_yes = True - - # if enable_helm_operator is not None: - # config.enable_helm_operator = enable_helm_operator - # update_yes = True - - # # Get the helm operator properties from the config and set them - # if config.helm_operator_properties is None: - # config.helm_operator_properties = HelmOperatorProperties() - # if helm_operator_chart_version is not None: - # config.helm_operator_properties.chart_version = helm_operator_chart_version.strip() - # update_yes = True - # if helm_operator_params is not None: - # config.helm_operator_properties.chart_values = helm_operator_params.strip() - # update_yes = True - - # if update_yes is False: - # raise RequiredArgumentMissingError( - # 'Invalid update. No values to update!', - # 'Verify that at least one changed parameter is provided in the update command') - - # # Flag which parameters have been set and validate these settings against the set repository url - # known_hosts_contents_set = config.ssh_known_hosts_contents != "" - # validate_url_with_params(config.repository_url, - # ssh_private_key_set=False, - # known_hosts_contents_set=known_hosts_contents_set, - # https_auth_set=False) - - # config = client.create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, - # source_control_configuration_name, config) - - # return __fix_compliance_state(config) - - -def list_k8s_configuration(client, resource_group_name, cluster_name, cluster_type): - cluster_rp = _get_cluster_type(cluster_type) - return client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - - -def delete_k8s_configuration(client, resource_group_name, cluster_name, name, cluster_type): - """Delete an existing Kubernetes Source Control Configuration. - - """ - # Determine ClusterRP - cluster_rp = _get_cluster_type(cluster_type) - - source_control_configuration_name = name - - return client.delete(resource_group_name, cluster_rp, cluster_type, cluster_name, source_control_configuration_name) - - -def _get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key): - protected_settings = {} - ssh_private_key_data = _get_data_from_key_or_file(ssh_private_key, ssh_private_key_file) +def flux_config_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, + scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, + branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None, + ssh_private_key_file=None, https_user=None, https_key=None, known_hosts=None, + known_hosts_file=None, suspend=False, kustomization=None, no_wait=False): + + provider = FluxConfigurationProvider(cmd) + return provider.create(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, kind, + timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, ssh_private_key, + ssh_private_key_file, https_user, https_key, known_hosts, known_hosts_file, suspend, + kustomization, no_wait) + + +def flux_config_create_source(cmd, client, resource_group_name, cluster_type, cluster_name, name, url=None, + scope='cluster', namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, + branch=None, tag=None, semver=None, commit=None, local_auth_ref=None, + ssh_private_key=None, ssh_private_key_file=None, https_user=None, https_key=None, + known_hosts=None, known_hosts_file=None): + + provider = FluxConfigurationProvider(cmd) + return provider.create_source(resource_group_name, cluster_type, cluster_name, name, url, scope, namespace, + kind, timeout, sync_interval, branch, tag, semver, commit, local_auth_ref, + ssh_private_key, ssh_private_key_file, https_user, https_key, known_hosts, + known_hosts_file) + + +def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_type, cluster_name, name, + kustomization_name, dependencies=None, timeout=None, sync_interval=None, + retry_interval=None, path='', prune=False, validation='none', force=False): + + provider = FluxConfigurationProvider(cmd) + return provider.create_kustomization(resource_group_name, cluster_type, cluster_name, name, kustomization_name, + dependencies, timeout, sync_interval, retry_interval, path, prune, + validation, force) + + +def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False, yes=False): + provider = FluxConfigurationProvider(cmd) + return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait, yes) + + +# Extension Methods + +def extension_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): + provider = ExtensionProvider(cmd) + return provider.show(resource_group_name, cluster_type, cluster_name, name) + + +def extension_list(cmd, client, resource_group_name, cluster_type, cluster_name): + provider = ExtensionProvider(cmd) + return provider.list(resource_group_name, cluster_type, cluster_name) + + +def extension_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, + extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, + version=None, target_namespace=None, release_namespace=None, configuration_settings=None, + configuration_protected_settings=None, configuration_settings_file=None, + configuration_protected_settings_file=None, tags=None, no_wait=False): + provider = ExtensionProvider(cmd) + return provider.create(resource_group_name, cluster_type, cluster_name, name, extension_type, scope, + auto_upgrade_minor_version, release_train, version, target_namespace, + release_namespace, configuration_settings, configuration_protected_settings, + configuration_settings_file, configuration_protected_settings_file) - # Add gitops private key data to protected settings if exists - # Dry-run all key types to determine if the private key is in a valid format - if ssh_private_key_data != '': - _validate_private_key(ssh_private_key_data) - protected_settings["sshPrivateKey"] = ssh_private_key_data - # Check if both httpsUser and httpsKey exist, then add to protected settings - if https_user != '' and https_key != '': - protected_settings['httpsUser'] = _to_base64(https_user) - protected_settings['httpsKey'] = _to_base64(https_key) - elif https_user != '': - raise RequiredArgumentMissingError( - 'Error! --https-user used without --https-key', - 'Try providing both --https-user and --https-key together') - elif https_key != '': - raise RequiredArgumentMissingError( - 'Error! --http-key used without --http-user', - 'Try providing both --https-user and --https-key together') - - return protected_settings +def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False): + provider = ExtensionProvider(cmd) + return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait) diff --git a/src/k8s-config/azext_k8s_config/format.py b/src/k8s-configuration/azext_k8s_configuration/format.py similarity index 64% rename from src/k8s-config/azext_k8s_config/format.py rename to src/k8s-configuration/azext_k8s_configuration/format.py index 2f6447dd625..dec0aa81180 100644 --- a/src/k8s-config/azext_k8s_config/format.py +++ b/src/k8s-configuration/azext_k8s_configuration/format.py @@ -6,21 +6,22 @@ from collections import OrderedDict -def extension_list_table_format(results): - return [__get_extension_table_row(result) for result in results] +def sourcecontrol_list_table_format(results): + return [__get_sourcecontrolconfig_table_row(result) for result in results] -def extension_show_table_format(result): - return __get_extension_table_row(result) +def sourcecontrol_show_table_format(result): + return __get_sourcecontrolconfig_table_row(result) -def __get_extension_table_row(result): +def __get_sourcecontrolconfig_table_row(result): return OrderedDict([ ('name', result['name']), - ('extensionType', result['extensionType']), - ('version', result['version']), - ('provisioningState', result['provisioningState']), - ('lastModifiedAt', result['systemData']['lastModifiedAt']) + ('repositoryUrl', result['repositoryUrl']), + ('operatorName', result['operatorInstanceName']), + ('operatorNamespace', result['operatorNamespace']), + ('scope', result['operatorScope']), + ('provisioningState', result['provisioningState']) ]) diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureDefender.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/AzureDefender.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureDefender.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureMLKubernetes.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/AzureMLKubernetes.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureMLKubernetes.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/Cassandra.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/Cassandra.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/Cassandra.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/ContainerInsights.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/ContainerInsights.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/ContainerInsights.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtension.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtension.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtension.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtensionWithIdentity.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/DefaultExtensionWithIdentity.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtensionWithIdentity.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/OpenServiceMesh.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/OpenServiceMesh.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/OpenServiceMesh.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/PartnerExtensionModel.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/PartnerExtensionModel.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/PartnerExtensionModel.py diff --git a/src/k8s-config/azext_k8s_config/partner_extensions/__init__.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/partner_extensions/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/partner_extensions/__init__.py diff --git a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/ExtensionProvider.py similarity index 98% rename from src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py rename to src/k8s-configuration/azext_k8s_configuration/providers/ExtensionProvider.py index 2d4d2537fc4..b3b7321a886 100644 --- a/src/k8s-config/azext_k8s_config/providers/ExtensionProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/ExtensionProvider.py @@ -29,7 +29,7 @@ ) from .._client_factory import cf_resources -from .._client_factory import k8s_config_extension_client +from .._client_factory import k8s_configuration_extension_client from .. import consts @@ -53,7 +53,7 @@ def ExtensionFactory(extension_name): class ExtensionProvider: def __init__(self, cmd): self.cmd = cmd - self.client = k8s_config_extension_client(cmd.cli_ctx) + self.client = k8s_configuration_extension_client(cmd.cli_ctx) def show(self, resource_group_name, cluster_type, cluster_name, name): # Determine ClusterRP diff --git a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py similarity index 98% rename from src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py rename to src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py index 0e1741611dd..229ad4fa7a8 100644 --- a/src/k8s-config/azext_k8s_config/providers/FluxConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py @@ -7,7 +7,7 @@ import os from re import L -from azext_k8s_config.confirm import user_confirmation_factory +from ..confirm import user_confirmation_factory from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property @@ -15,7 +15,7 @@ from azure.core.exceptions import HttpResponseError from knack.log import get_logger -from .._client_factory import k8s_config_fluxconfig_client +from .._client_factory import k8s_configuration_fluxconfig_client from ..utils import get_cluster_rp, get_data_from_key_or_file, get_duration, has_prune_enabled, to_base64 from ..validators import ( validate_cc_registration, @@ -45,7 +45,7 @@ def __init__(self, cmd): self.extension_provider = ExtensionProvider(cmd) self.source_control_configuration_provider = SourceControlConfigurationProvider(cmd) self.cmd = cmd - self.client = k8s_config_fluxconfig_client(cmd.cli_ctx) + self.client = k8s_configuration_fluxconfig_client(cmd.cli_ctx) def show(self, resource_group_name, cluster_type, cluster_name, name): """Get an existing Kubernetes Source Control Configuration. diff --git a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/SourceControlConfigurationProvider.py similarity index 96% rename from src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py rename to src/k8s-configuration/azext_k8s_configuration/providers/SourceControlConfigurationProvider.py index 30f5d9bc3dc..c2dbbe32fef 100644 --- a/src/k8s-config/azext_k8s_config/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/SourceControlConfigurationProvider.py @@ -3,12 +3,12 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from azext_k8s_config.validators import validate_cc_registration, validate_known_hosts, validate_url_with_params +from ..validators import validate_cc_registration, validate_known_hosts, validate_url_with_params from azure.cli.core.azclierror import ResourceNotFoundError from azure.core.exceptions import HttpResponseError from knack.log import get_logger -from .._client_factory import k8s_config_sourcecontrol_client +from .._client_factory import k8s_configuration_sourcecontrol_client from ..utils import fix_compliance_state, get_cluster_rp, get_data_from_key_or_file, to_base64 from .. import consts @@ -23,7 +23,7 @@ class SourceControlConfigurationProvider: def __init__(self, cmd): self.cmd = cmd - self.client = k8s_config_sourcecontrol_client(cmd.cli_ctx) + self.client = k8s_configuration_sourcecontrol_client(cmd.cli_ctx) def show(self, resource_group_name, cluster_type, cluster_name, name): # Determine ClusterRP diff --git a/src/k8s-config/azext_k8s_config/providers/__init__.py b/src/k8s-configuration/azext_k8s_configuration/providers/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/providers/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/providers/__init__.py diff --git a/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/cert_and_key_encoded.txt b/src/k8s-configuration/azext_k8s_configuration/tests/latest/data/azure_ml/cert_and_key_encoded.txt similarity index 100% rename from src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/cert_and_key_encoded.txt rename to src/k8s-configuration/azext_k8s_configuration/tests/latest/data/azure_ml/cert_and_key_encoded.txt diff --git a/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_cert.pem b/src/k8s-configuration/azext_k8s_configuration/tests/latest/data/azure_ml/test_cert.pem similarity index 100% rename from src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_cert.pem rename to src/k8s-configuration/azext_k8s_configuration/tests/latest/data/azure_ml/test_cert.pem diff --git a/src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_key.pem b/src/k8s-configuration/azext_k8s_configuration/tests/latest/data/azure_ml/test_key.pem similarity index 100% rename from src/k8s-config/azext_k8s_config/tests/latest/data/azure_ml/test_key.pem rename to src/k8s-configuration/azext_k8s_configuration/tests/latest/data/azure_ml/test_key.pem diff --git a/src/k8s-configuration/azext_k8s_configuration/tests/latest/recordings/test_k8s_configuration_success.yaml b/src/k8s-configuration/azext_k8s_configuration/tests/latest/recordings/test_k8s_configuration_success.yaml deleted file mode 100644 index df066387443..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/tests/latest/recordings/test_k8s_configuration_success.yaml +++ /dev/null @@ -1,441 +0,0 @@ -interactions: -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration show - Connection: - - keep-alive - ParameterSetName: - - -g -c -n --cluster-type - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config10?api-version=2021-03-01 - response: - body: - string: '{"error":{"code":"ResourceNotFound","message":"SourceControlConfiguration - with name ''cli-test-config10'' not found."}}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '117' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:01 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - x-content-type-options: - - nosniff - status: - code: 404 - message: Not Found -- request: - body: '{"properties": {"repositoryUrl": "git://github.com/anubhav929/flux-get-started", - "operatorNamespace": "cli-test-config10-opns", "operatorInstanceName": "cli-test-config10-opin", - "operatorType": "flux", "operatorParams": "--git-readonly ", "configurationProtectedSettings": - {"sshPrivateKey": "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFZRUFxZlBtNlc3YkVLTmVvN3VCQzhTMXYydUpPS1NZWGNmanlpVEk2djNkZUhRSjJtMGFRajB0CmtwM05qMUZkRUsrMkVXTy9xNGFkWUpaS0ZZSjluWTZyREZOSXBZdmVWaVNUQjhITzI5VVdySTRLVGZMRGhiVmVCV0pjQVcKMkFpZ0ZnTU5qdTZXa0JVL1NWK1FCVHJiRVl6RFhpOTVNR1ZveTVKV3drdkdtakRaOHFSaEFxbU0rdUF4S1I4Z1lyRllPZgpRbC9zM2I5ajJKQ1VtVFlwYkxqMkJPd0JNQ1J3NlFQY0lVcVlaaUl3MUNNaXZKZ2tVQTdwUlRCZHVsYXlXNWQ2MTl4RFNsCmZ6N1JuU0tKM3RwanEwZThBTmtkU1h4SjQrMXhpNm5IM0lVY1ZBM1NzcVhWam80ak5sNU5EWkJlTDNpQ0xXSVZYUkpDemsKNGg3a2pXVkQ3UnNDNGJDOTF6MzlZMDlnK3ZIdjErZFplUmNYZWIvNkFzbTBEeHVhRGo2cVVCVm9JOWkwbzFKbndiMnA0MQpGV2prazljc054a2dnajMzU3ozTWJRTVN0bTFLaWU2bHNRamlMUXdGT3Qwd3lFTnova2RUR25idkVMUTN3aWdUdVFrelFOCnlMR2dmK3FXZnhqL1l1MWt5b0xrQVpqT3JxdEttalVILzk3Y3lncWhBQUFGa08zNi9uWHQrdjUxQUFBQUIzTnphQzF5YzIKRUFBQUdCQUtuejV1bHUyeENqWHFPN2dRdkV0YjlyaVRpa21GM0g0OG9reU9yOTNYaDBDZHB0R2tJOUxaS2R6WTlSWFJDdgp0aEZqdjZ1R25XQ1dTaFdDZloyT3F3eFRTS1dMM2xZa2t3ZkJ6dHZWRnF5T0NrM3l3NFcxWGdWaVhBRnRnSW9CWUREWTd1CmxwQVZQMGxma0FVNjJ4R013MTR2ZVRCbGFNdVNWc0pMeHBvdzJmS2tZUUtwalByZ01Ta2ZJR0t4V0RuMEpmN04yL1k5aVEKbEprMktXeTQ5Z1RzQVRBa2NPa0QzQ0ZLbUdZaU1OUWpJcnlZSkZBTzZVVXdYYnBXc2x1WGV0ZmNRMHBYOCswWjBpaWQ3YQpZNnRIdkFEWkhVbDhTZVB0Y1l1cHg5eUZIRlFOMHJLbDFZNk9JelplVFEyUVhpOTRnaTFpRlYwU1FzNU9JZTVJMWxRKzBiCkF1R3d2ZGM5L1dOUFlQcng3OWZuV1hrWEYzbS8rZ0xKdEE4Ym1nNCtxbEFWYUNQWXRLTlNaOEc5cWVOUlZvNUpQWExEY1oKSUlJOTkwczl6RzBERXJadFNvbnVwYkVJNGkwTUJUcmRNTWhEYy81SFV4cDI3eEMwTjhJb0U3a0pNMERjaXhvSC9xbG44WQovMkx0Wk1xQzVBR1l6cTZyU3BvMUIvL2UzTW9Lb1FBQUFBTUJBQUVBQUFHQkFKSnJUVTlqY0Z4ZlE1UHdZUGRRbS95MG10CjR3QUEwYnY0WlNOcjh0dy9hWWtqeWFybnJPMWtwd3BiNkpySkpKcjZRL3Vjdi9CK3RFejhMRVQ1REViMTBKQzVlRWJ5THMKRTdnbEl5Q0Y3eWp1bnJZVkpwbzFiVEZhVWtYd24wTkdlQ2JkWHNlODdhWDFISmdQemdmZ2dhcTk2aks5ZWtKcXJzQXM4VwpGWjZWNDgrR0N3WU9LU1dpclBmdWx5b3YvQURCOVZJVzdTQ3lWek9uTGRGTWRVZXJBMjI3Y3NUaEtTZnI0MzFDQjU2SE43CmFkdnRmNnR4alV0TXBoTjV5ZVBiRmxVZS9Wb2VQY1hNdXA4OXN3V2gvd3ZScklCbytUYXo2SzQxcGFzOEVObjFyemFxL3kKRHlWelJuSGtlMGhKR2ZZelJhbzlZQm5jeHFMOCtXdDQxZFFzQUdhdlIwd3ZNSit5TFpuR0x5amVXaVZkcExjT0FWSGpIOQpITGMrTDdnaGpIZ1VidDNDWG9Wd0gyWktnelI5cmk3bU93YnorejZsN1pwWjlQalJxeU1HcTloYU5vNHVEdjJqbWhGNlZVClBMU2Q3WTczWCtWTFAvWUZqbTBlUzJUbGFRQ3E2Vms0dzJqSHVWcXorcng4SllYb2tidFZXYnFYcmg3VzF5VGk4MXVRQUEKQU1Ba0JaQzF0SThvd29SNDYvL1h1SWQxQjBGRUhGUXBvSHFuVGNSVlVKS2RXb2xJRU5tYVVtdG1UZFVicVYyNGJMa1RtZQpiWHZQdlF3LzJoVk5VVmhWbDNjays1SUZBS0hYVWJ3ZklSWE8vUVlUbFM0ZVdabkFsN0JQSzJQa080SXkvOG1zQVZKRGl4CmkvVm1oaTBYb05lSmxERU9sdzNaY084aTlRZjVSbTNEWmRHUDRha0JsYmk5ekdBWUpqRGFjM0dWdTMxK2pJVG9hUHplbysKeUFDL2svM0J5Slg4enQ1cDRHVXpsNVFKcEVHMnBpQXdJeElKZS8yK3pBMXU5dmhma0FBQURCQU5NZHdhemx5MXNpd0dXbQpJWSs4VFZMN1EwQ1pFTWxTL0VraE1YM2FNQnZYaURXd2cwVk8zKytXUDhlMWhDSUxvNmdqL0N2dFdLdGEzVlozUWFScHZ5CkhCVEp4Q205NHZQOXFPelhTRGZ0WVRrSHh1SFdQaklhb010N0YyL0srejJiZTdESmhvL0ZwMVY0U2x2R1ljWHdqaWhEaDAKbHF1bUltOEJJei9taHpjZTFKR0VMUUdJeXk4RDI0dTNtY2NhSFoxYWY1V3A5Y1VCZ09POXEwa3B1WVhEdHpPSk9UTVozUQpNUm5xdXVVM1ppRHdmRGltZzdsZktwWGkxZzFxeWZUd0FBQU1FQXpoWEdhTVdBM1pUT1hqWWhPTUhkdTk0R2RNcHNXYWo0CjBsMmZ6YzdFWTlzWEdLZ01XMllvRXk5UVNSTDRPUmNMaUFKTDRLZGdZeGZzeVdma1U1d21TbGZXNjlrb0R2WTE0LzNWbWYKZ0NTUkxvL0RnTUZtOGFNK3pUVzhWYTVpclJXWFpEeHNXb0RiNzdIZ2JZaE90M29iOEFWWUh4akk3N1k3MXlBUzhXS2xRSQpYQi9qZ01vN1BCL3BTMVVYSEhCcndxQkdwM3M5aThab0E0L2hLY0pvaEtWSDZGL0Z2Rk1jWHZTNjZOcGNUWHNWQzBVUzNkCkJVY0taNTVvUUhVcnNQQUFBQUdIQnlZWFJvYVd0eVFFeEJVRlJQVUMxU00wZFVUa2xDVXdFQwotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K"}, - "operatorScope": "namespace", "sshKnownHostsContents": "Z2l0b3BzLWJpdGJ1Y2tldC10ZXN0LXNlcnZlci5lYXN0dXMuY2xvdWRhcHAuYXp1cmUuY29tIHNzaC1yc2EgQUFBQUIzTnphQzF5YzJFQUFBQURBUUFCQUFBQkFRQytNT0w3bjk2aGs3emVmMDNwak9vMGF3UENISkZ4NU04TjJ2L2tvODgvc202Y2VzOFljdnYyL0hoUlhRSFZHRUxqZjNuTXVGSVJPMEdMdTFabFNreGRUTUhGcXBxYzFjcUM2R3kveUJXRGM1SWFwWnJBMXFxeSsrZVdpelAzQXdMbWsrMUhXWGdtcHljZUtYNU9vd3VNT3cwd3RYRUdTcDhtVk0wV2VpUzEwWnZ5ZVVKK04zbkNvczMyWDhIeVpnc1pMUS9zSTB4NXN6ODQ2am5JZEFOckZsYU9MUTJ1ejRUa0M2ekNvd3lIdzlLWXJ5V2hJZDAraCt5SXQ5dUtqVHZsWFNpdm1ISjViZzdUWWlkbnFtbjI0UGE4WnFpbTE5UGszUjg0cW9qclVmYm1XT3VwUjdYNXZVVWZqYzhERFRxa3FnRmkxcWdVdE1mWGlMRXErZFVa", - "enableHelmOperator": true, "helmOperatorProperties": {"chartVersion": "1.2.0", - "chartValues": "--set git.ssh.secretName=gitops-privatekey-cli-test-config10-opin - --set tillerNamespace=kube-system"}}}' - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration create - Connection: - - keep-alive - Content-Length: - - '4614' - Content-Type: - - application/json; charset=utf-8 - ParameterSetName: - - -g -n -c -u --cluster-type --scope --operator-instance-name --operator-namespace - --operator-params --git-readonly --ssh-private-key --ssh-known-hosts --enable-helm-operator - --helm-operator-chart-version --helm-operator-params --set git.ssh.secretName - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: PUT - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config10?api-version=2021-03-01 - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config10","name":"cli-test-config10","type":"Microsoft.KubernetesConfiguration/sourceControlConfigurations","properties":{"operatorNamespace":"cli-test-config10-opns","provisioningState":"Succeeded","complianceStatus":{"complianceState":"Pending","lastConfigApplied":"0001-01-01T00:00:00+00:00","message":"{\"OperatorMessage\":null,\"ClusterState\":null}","messageLevel":"Information"},"enableHelmOperator":true,"helmOperatorProperties":{"chartVersion":"1.2.0","chartValues":"--set - git.ssh.secretName=gitops-privatekey-cli-test-config10-opin --set tillerNamespace=kube-system"},"repositoryUrl":"git://github.com/anubhav929/flux-get-started","operatorInstanceName":"cli-test-config10-opin","operatorType":"Flux","operatorScope":"namespace","operatorParams":"--git-readonly","sshKnownHostsContents":"Z2l0b3BzLWJpdGJ1Y2tldC10ZXN0LXNlcnZlci5lYXN0dXMuY2xvdWRhcHAuYXp1cmUuY29tIHNzaC1yc2EgQUFBQUIzTnphQzF5YzJFQUFBQURBUUFCQUFBQkFRQytNT0w3bjk2aGs3emVmMDNwak9vMGF3UENISkZ4NU04TjJ2L2tvODgvc202Y2VzOFljdnYyL0hoUlhRSFZHRUxqZjNuTXVGSVJPMEdMdTFabFNreGRUTUhGcXBxYzFjcUM2R3kveUJXRGM1SWFwWnJBMXFxeSsrZVdpelAzQXdMbWsrMUhXWGdtcHljZUtYNU9vd3VNT3cwd3RYRUdTcDhtVk0wV2VpUzEwWnZ5ZVVKK04zbkNvczMyWDhIeVpnc1pMUS9zSTB4NXN6ODQ2am5JZEFOckZsYU9MUTJ1ejRUa0M2ekNvd3lIdzlLWXJ5V2hJZDAraCt5SXQ5dUtqVHZsWFNpdm1ISjViZzdUWWlkbnFtbjI0UGE4WnFpbTE5UGszUjg0cW9qclVmYm1XT3VwUjdYNXZVVWZqYzhERFRxa3FnRmkxcWdVdE1mWGlMRXErZFVa","configurationProtectedSettings":{},"repositoryPublicKey":""},"systemData":{"createdBy":null,"createdByType":null,"createdAt":"2021-02-10T22:59:03.2209+00:00","lastModifiedBy":null,"lastModifiedByType":null,"lastModifiedAt":"2021-02-10T22:59:03.2209001+00:00"}}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '1876' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:02 GMT - expires: - - '-1' - location: - - file:///subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config10 - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - x-content-type-options: - - nosniff - x-ms-ratelimit-remaining-subscription-writes: - - '1199' - status: - code: 201 - message: Created -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration show - Connection: - - keep-alive - ParameterSetName: - - -g -c -n --cluster-type - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config10?api-version=2021-03-01 - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config10","name":"cli-test-config10","type":"Microsoft.KubernetesConfiguration/sourceControlConfigurations","properties":{"operatorNamespace":"cli-test-config10-opns","provisioningState":"Succeeded","complianceStatus":{"complianceState":"Pending","lastConfigApplied":"0001-01-01T00:00:00+00:00","message":"{\"OperatorMessage\":null,\"ClusterState\":null}","messageLevel":"Information"},"enableHelmOperator":true,"helmOperatorProperties":{"chartVersion":"1.2.0","chartValues":"--set - git.ssh.secretName=gitops-privatekey-cli-test-config10-opin --set tillerNamespace=kube-system"},"repositoryUrl":"git://github.com/anubhav929/flux-get-started","operatorInstanceName":"cli-test-config10-opin","operatorType":"Flux","operatorScope":"namespace","operatorParams":"--git-readonly","sshKnownHostsContents":"Z2l0b3BzLWJpdGJ1Y2tldC10ZXN0LXNlcnZlci5lYXN0dXMuY2xvdWRhcHAuYXp1cmUuY29tIHNzaC1yc2EgQUFBQUIzTnphQzF5YzJFQUFBQURBUUFCQUFBQkFRQytNT0w3bjk2aGs3emVmMDNwak9vMGF3UENISkZ4NU04TjJ2L2tvODgvc202Y2VzOFljdnYyL0hoUlhRSFZHRUxqZjNuTXVGSVJPMEdMdTFabFNreGRUTUhGcXBxYzFjcUM2R3kveUJXRGM1SWFwWnJBMXFxeSsrZVdpelAzQXdMbWsrMUhXWGdtcHljZUtYNU9vd3VNT3cwd3RYRUdTcDhtVk0wV2VpUzEwWnZ5ZVVKK04zbkNvczMyWDhIeVpnc1pMUS9zSTB4NXN6ODQ2am5JZEFOckZsYU9MUTJ1ejRUa0M2ekNvd3lIdzlLWXJ5V2hJZDAraCt5SXQ5dUtqVHZsWFNpdm1ISjViZzdUWWlkbnFtbjI0UGE4WnFpbTE5UGszUjg0cW9qclVmYm1XT3VwUjdYNXZVVWZqYzhERFRxa3FnRmkxcWdVdE1mWGlMRXErZFVa","configurationProtectedSettings":{},"repositoryPublicKey":""},"systemData":{"createdBy":null,"createdByType":null,"createdAt":"2021-02-10T22:59:03.2209+00:00","lastModifiedBy":null,"lastModifiedByType":null,"lastModifiedAt":"2021-02-10T22:59:03.2209001+00:00"}}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '1876' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:03 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding,Accept-Encoding - x-content-type-options: - - nosniff - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration delete - Connection: - - keep-alive - Content-Length: - - '0' - ParameterSetName: - - -g -c -n --cluster-type -y - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: DELETE - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config10?api-version=2021-03-01 - response: - body: - string: '{"version":"1.1","content":null,"statusCode":200,"reasonPhrase":"OK","headers":[],"trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '152' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:05 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding - x-content-type-options: - - nosniff - x-ms-ratelimit-remaining-subscription-deletes: - - '14999' - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration show - Connection: - - keep-alive - ParameterSetName: - - -g -c -n --cluster-type - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config11?api-version=2021-03-01 - response: - body: - string: '{"error":{"code":"ResourceNotFound","message":"SourceControlConfiguration - with name ''cli-test-config11'' not found."}}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '117' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:05 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - x-content-type-options: - - nosniff - status: - code: 404 - message: Not Found -- request: - body: '{"properties": {"repositoryUrl": "https://github.com/jonathan-innis/helm-operator-get-started-private.git", - "operatorNamespace": "cli-test-config11-opns", "operatorInstanceName": "cli-test-config11-opin", - "operatorType": "flux", "operatorParams": "--git-readonly ", "configurationProtectedSettings": - {"httpsUser": "ZmFrZS11c2VybmFtZQ==", "httpsKey": "ZmFrZXBhc3N3b3JkdGhhdGl3b3VsZHVzZWZvcmdpdGh1Yg=="}, - "operatorScope": "namespace", "sshKnownHostsContents": "", "enableHelmOperator": - true, "helmOperatorProperties": {"chartVersion": "1.2.0", "chartValues": "--set - tillerNamespace=kube-system"}}}' - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration create - Connection: - - keep-alive - Content-Length: - - '595' - Content-Type: - - application/json; charset=utf-8 - ParameterSetName: - - -g -n -c -u --cluster-type --scope --operator-instance-name --operator-namespace - --operator-params --git-readonly --https-user --https-key --enable-helm-operator - --helm-operator-chart-version --helm-operator-params --set tillerNamespace - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: PUT - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config11?api-version=2021-03-01 - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config11","name":"cli-test-config11","type":"Microsoft.KubernetesConfiguration/sourceControlConfigurations","properties":{"operatorNamespace":"cli-test-config11-opns","provisioningState":"Succeeded","complianceStatus":{"complianceState":"Pending","lastConfigApplied":"0001-01-01T00:00:00+00:00","message":"{\"OperatorMessage\":null,\"ClusterState\":null}","messageLevel":"Information"},"enableHelmOperator":true,"helmOperatorProperties":{"chartVersion":"1.2.0","chartValues":"--set - tillerNamespace=kube-system"},"repositoryUrl":"https://github.com/jonathan-innis/helm-operator-get-started-private.git","operatorInstanceName":"cli-test-config11-opin","operatorType":"Flux","operatorScope":"namespace","operatorParams":"--git-readonly","sshKnownHostsContents":"","configurationProtectedSettings":{},"repositoryPublicKey":""},"systemData":{"createdBy":null,"createdByType":null,"createdAt":"2021-02-10T22:59:07.5893423+00:00","lastModifiedBy":null,"lastModifiedByType":null,"lastModifiedAt":"2021-02-10T22:59:07.5893424+00:00"}}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '1260' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:07 GMT - expires: - - '-1' - location: - - file:///subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config11 - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - x-content-type-options: - - nosniff - x-ms-ratelimit-remaining-subscription-writes: - - '1199' - status: - code: 201 - message: Created -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration show - Connection: - - keep-alive - ParameterSetName: - - -g -c -n --cluster-type - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: GET - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config11?api-version=2021-03-01 - response: - body: - string: '{"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config11","name":"cli-test-config11","type":"Microsoft.KubernetesConfiguration/sourceControlConfigurations","properties":{"operatorNamespace":"cli-test-config11-opns","provisioningState":"Succeeded","complianceStatus":{"complianceState":"Pending","lastConfigApplied":"0001-01-01T00:00:00+00:00","message":"{\"OperatorMessage\":null,\"ClusterState\":null}","messageLevel":"Information"},"enableHelmOperator":true,"helmOperatorProperties":{"chartVersion":"1.2.0","chartValues":"--set - tillerNamespace=kube-system"},"repositoryUrl":"https://github.com/jonathan-innis/helm-operator-get-started-private.git","operatorInstanceName":"cli-test-config11-opin","operatorType":"Flux","operatorScope":"namespace","operatorParams":"--git-readonly","sshKnownHostsContents":"","configurationProtectedSettings":{},"repositoryPublicKey":""},"systemData":{"createdBy":null,"createdByType":null,"createdAt":"2021-02-10T22:59:07.5893423+00:00","lastModifiedBy":null,"lastModifiedByType":null,"lastModifiedAt":"2021-02-10T22:59:07.5893424+00:00"}}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '1260' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:08 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding,Accept-Encoding - x-content-type-options: - - nosniff - status: - code: 200 - message: OK -- request: - body: null - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - CommandName: - - k8s-configuration delete - Connection: - - keep-alive - Content-Length: - - '0' - ParameterSetName: - - -g -c -n --cluster-type -y - User-Agent: - - python/3.9.0 (Windows-10-10.0.19041-SP0) msrest/0.6.21 msrest_azure/0.6.4 - azure-mgmt-kubernetesconfiguration/0.2.0 Azure-SDK-For-Python AZURECLI/2.19.1 - accept-language: - - en-US - method: DELETE - uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/nanthirg0923/providers/Microsoft.Kubernetes/connectedClusters/nanthicluster0923/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/cli-test-config11?api-version=2021-03-01 - response: - body: - string: '{"version":"1.1","content":null,"statusCode":200,"reasonPhrase":"OK","headers":[],"trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true}' - headers: - api-supported-versions: - - 2019-11-01-Preview, 2020-07-01-Preview, 2020-10-01-Preview, 2021-03-01 - cache-control: - - no-cache - content-length: - - '152' - content-type: - - application/json; charset=utf-8 - date: - - Wed, 10 Feb 2021 22:59:08 GMT - expires: - - '-1' - pragma: - - no-cache - server: - - openresty/1.15.8.2 - strict-transport-security: - - max-age=31536000; includeSubDomains - transfer-encoding: - - chunked - vary: - - Accept-Encoding - x-content-type-options: - - nosniff - x-ms-ratelimit-remaining-subscription-deletes: - - '14999' - status: - code: 200 - message: OK -version: 1 diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_azureml_extension.py b/src/k8s-configuration/azext_k8s_configuration/tests/latest/test_azureml_extension.py similarity index 100% rename from src/k8s-config/azext_k8s_config/tests/latest/test_azureml_extension.py rename to src/k8s-configuration/azext_k8s_configuration/tests/latest/test_azureml_extension.py diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py b/src/k8s-configuration/azext_k8s_configuration/tests/latest/test_k8s-config_scenario.py similarity index 100% rename from src/k8s-config/azext_k8s_config/tests/latest/test_k8s-config_scenario.py rename to src/k8s-configuration/azext_k8s_configuration/tests/latest/test_k8s-config_scenario.py diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py b/src/k8s-configuration/azext_k8s_configuration/tests/latest/test_k8s_extension_scenario.py similarity index 100% rename from src/k8s-config/azext_k8s_config/tests/latest/test_k8s_extension_scenario.py rename to src/k8s-configuration/azext_k8s_configuration/tests/latest/test_k8s_extension_scenario.py diff --git a/src/k8s-config/azext_k8s_config/tests/latest/test_open_service_mesh.py b/src/k8s-configuration/azext_k8s_configuration/tests/latest/test_open_service_mesh.py similarity index 100% rename from src/k8s-config/azext_k8s_config/tests/latest/test_open_service_mesh.py rename to src/k8s-configuration/azext_k8s_configuration/tests/latest/test_open_service_mesh.py diff --git a/src/k8s-config/azext_k8s_config/utils.py b/src/k8s-configuration/azext_k8s_configuration/utils.py similarity index 100% rename from src/k8s-config/azext_k8s_config/utils.py rename to src/k8s-configuration/azext_k8s_configuration/utils.py diff --git a/src/k8s-config/azext_k8s_config/validators.py b/src/k8s-configuration/azext_k8s_configuration/validators.py similarity index 98% rename from src/k8s-config/azext_k8s_config/validators.py rename to src/k8s-configuration/azext_k8s_configuration/validators.py index 8330b5d9ad7..43449950443 100644 --- a/src/k8s-config/azext_k8s_config/validators.py +++ b/src/k8s-configuration/azext_k8s_configuration/validators.py @@ -42,6 +42,11 @@ def validate_fluxconfig_name(namespace): __validate_k8s_cr_name(namespace.name, "--name", 63) +def validate_operator_instance_name(namespace): + if namespace.operator_instance_name: + __validate_k8s_name(namespace.operator_instance_name, "--operator-instance-name", 23) + + def validate_operator_namespace(namespace): if namespace.operator_namespace: __validate_k8s_name(namespace.operator_namespace, "--operator-namespace", 23) diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/__init__.py index 874177b4d34..b0a136e072d 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/__init__.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/__init__.py @@ -1,19 +1,16 @@ # 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. -# +# 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. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._configuration import SourceControlConfigurationClientConfiguration from ._source_control_configuration_client import SourceControlConfigurationClient -__all__ = ['SourceControlConfigurationClient', 'SourceControlConfigurationClientConfiguration'] - -from .version import VERSION - -__version__ = VERSION +__all__ = ['SourceControlConfigurationClient'] +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_configuration.py index 5043ed69594..d6b853c02a3 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_configuration.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_configuration.py @@ -8,42 +8,64 @@ # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- -from msrestazure import AzureConfiguration +from typing import TYPE_CHECKING -from .version import VERSION +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import TokenCredential + +class SourceControlConfigurationClientConfiguration(Configuration): + """Configuration for SourceControlConfigurationClient. -class SourceControlConfigurationClientConfiguration(AzureConfiguration): - """Configuration for SourceControlConfigurationClient Note that all parameters used to create this instance are saved as instance attributes. - :param credentials: Credentials needed for the client to connect to Azure. - :type credentials: :mod:`A msrestazure Credentials - object` - :param subscription_id: The Azure subscription ID. This is a - GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str - :param str base_url: Service URL """ def __init__( - self, credentials, subscription_id, base_url=None): - - if credentials is None: - raise ValueError("Parameter 'credentials' must not be None.") + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + 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.") - if not base_url: - base_url = 'https://management.azure.com' + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) - super(SourceControlConfigurationClientConfiguration, self).__init__(base_url) - - # Starting Autorest.Python 4.0.64, make connection pool activated by default - self.keep_alive = True - - self.add_user_agent('azure-mgmt-kubernetesconfiguration/{}'.format(VERSION)) - self.add_user_agent('Azure-SDK-For-Python') - - self.credentials = credentials + self.credential = credential self.subscription_id = subscription_id + self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) + kwargs.setdefault('sdk_moniker', 'azure-mgmt-kubernetesconfiguration/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_source_control_configuration_client.py index b27243fc208..825bb82bbfe 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_source_control_configuration_client.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_source_control_configuration_client.py @@ -9,47 +9,272 @@ # regenerated. # -------------------------------------------------------------------------- -from msrest.service_client import SDKClient -from msrest import Serializer, Deserializer +from typing import TYPE_CHECKING + +from azure.mgmt.core import ARMPipelineClient +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin +from msrest import Deserializer, Serializer from ._configuration import SourceControlConfigurationClientConfiguration -from .operations import SourceControlConfigurationsOperations -from .operations import Operations -from . import models +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpRequest, HttpResponse -class SourceControlConfigurationClient(SDKClient): - """Use these APIs to create Source Control Configuration resources through ARM, for Kubernetes Clusters. +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass - :ivar config: Configuration for client. - :vartype config: SourceControlConfigurationClientConfiguration +class SourceControlConfigurationClient(MultiApiClientMixin, _SDKClient): + """KubernetesConfiguration Client. - :ivar source_control_configurations: SourceControlConfigurations operations - :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.operations.SourceControlConfigurationsOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.kubernetesconfiguration.operations.Operations + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. - :param credentials: Credentials needed for the client to connect to Azure. - :type credentials: :mod:`A msrestazure Credentials - object` - :param subscription_id: The Azure subscription ID. This is a - GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str - :param str base_url: Service URL + :param api_version: API version to use if no profile is provided, or if missing in profile. + :type api_version: str + :param base_url: Service URL + :type base_url: str + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ + DEFAULT_API_VERSION = '2021-03-01' + _PROFILE_TAG = "azure.mgmt.kubernetesconfiguration.SourceControlConfigurationClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + def __init__( - self, credentials, subscription_id, base_url=None): + self, + credential, # type: "TokenCredential" + subscription_id, # type: str + api_version=None, # type: Optional[str] + base_url=None, # type: Optional[str] + profile=KnownProfiles.default, # type: KnownProfiles + **kwargs # type: Any + ): + if not base_url: + base_url = 'https://management.azure.com' + self._config = SourceControlConfigurationClientConfiguration(credential, subscription_id, **kwargs) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(SourceControlConfigurationClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 2020-07-01-preview: :mod:`v2020_07_01_preview.models` + * 2020-10-01-preview: :mod:`v2020_10_01_preview.models` + * 2021-03-01: :mod:`v2021_03_01.models` + * 2021-05-01-preview: :mod:`v2021_05_01_preview.models` + * 2021-06-01-preview: :mod:`v2021_06_01_preview.models` + """ + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview import models + return models + elif api_version == '2020-10-01-preview': + from .v2020_10_01_preview import models + return models + elif api_version == '2021-03-01': + from .v2021_03_01 import models + return models + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview import models + return models + elif api_version == '2021-06-01-preview': + from .v2021_06_01_preview import models + return models + raise ValueError("API version {} is not available".format(api_version)) + + @property + def cluster_extension_type(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ClusterExtensionTypeOperations` + """ + api_version = self._get_api_version('cluster_extension_type') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ClusterExtensionTypeOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'cluster_extension_type'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def cluster_extension_types(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ClusterExtensionTypesOperations` + """ + api_version = self._get_api_version('cluster_extension_types') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ClusterExtensionTypesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'cluster_extension_types'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def extension_type_versions(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`ExtensionTypeVersionsOperations` + """ + api_version = self._get_api_version('extension_type_versions') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ExtensionTypeVersionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'extension_type_versions'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def extensions(self): + """Instance depends on the API version: + + * 2020-07-01-preview: :class:`ExtensionsOperations` + * 2021-05-01-preview: :class:`ExtensionsOperations` + """ + api_version = self._get_api_version('extensions') + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview.operations import ExtensionsOperations as OperationClass + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import ExtensionsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'extensions'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def flux_config_operation_status(self): + """Instance depends on the API version: + + * 2021-06-01-preview: :class:`FluxConfigOperationStatusOperations` + """ + api_version = self._get_api_version('flux_config_operation_status') + if api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import FluxConfigOperationStatusOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'flux_config_operation_status'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def flux_configurations(self): + """Instance depends on the API version: + + * 2021-06-01-preview: :class:`FluxConfigurationsOperations` + """ + api_version = self._get_api_version('flux_configurations') + if api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import FluxConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'flux_configurations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def location_extension_types(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`LocationExtensionTypesOperations` + """ + api_version = self._get_api_version('location_extension_types') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import LocationExtensionTypesOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'location_extension_types'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def operation_status(self): + """Instance depends on the API version: + + * 2021-05-01-preview: :class:`OperationStatusOperations` + * 2021-06-01-preview: :class:`OperationStatusOperations` + """ + api_version = self._get_api_version('operation_status') + if api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import OperationStatusOperations as OperationClass + elif api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import OperationStatusOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'operation_status'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def operations(self): + """Instance depends on the API version: + + * 2020-07-01-preview: :class:`Operations` + * 2020-10-01-preview: :class:`Operations` + * 2021-03-01: :class:`Operations` + * 2021-05-01-preview: :class:`Operations` + * 2021-06-01-preview: :class:`Operations` + """ + api_version = self._get_api_version('operations') + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview.operations import Operations as OperationClass + elif api_version == '2020-10-01-preview': + from .v2020_10_01_preview.operations import Operations as OperationClass + elif api_version == '2021-03-01': + from .v2021_03_01.operations import Operations as OperationClass + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import Operations as OperationClass + elif api_version == '2021-06-01-preview': + from .v2021_06_01_preview.operations import Operations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - self.config = SourceControlConfigurationClientConfiguration(credentials, subscription_id, base_url) - super(SourceControlConfigurationClient, self).__init__(self.config.credentials, self.config) + @property + def source_control_configurations(self): + """Instance depends on the API version: - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - self.api_version = '2021-03-01' - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + * 2020-07-01-preview: :class:`SourceControlConfigurationsOperations` + * 2020-10-01-preview: :class:`SourceControlConfigurationsOperations` + * 2021-03-01: :class:`SourceControlConfigurationsOperations` + * 2021-05-01-preview: :class:`SourceControlConfigurationsOperations` + """ + api_version = self._get_api_version('source_control_configurations') + if api_version == '2020-07-01-preview': + from .v2020_07_01_preview.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2020-10-01-preview': + from .v2020_10_01_preview.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2021-03-01': + from .v2021_03_01.operations import SourceControlConfigurationsOperations as OperationClass + elif api_version == '2021-05-01-preview': + from .v2021_05_01_preview.operations import SourceControlConfigurationsOperations as OperationClass + else: + raise ValueError("API version {} does not have operation group 'source_control_configurations'".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) - self.source_control_configurations = SourceControlConfigurationsOperations( - self._client, self.config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self.config, self._serialize, self._deserialize) + def close(self): + self._client.close() + def __enter__(self): + self._client.__enter__() + return self + def __exit__(self, *exc_details): + self._client.__exit__(*exc_details) diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/_version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_version.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/_version.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_version.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/aio/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/models.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models.py diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py deleted file mode 100644 index 86f85f9bcb5..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py +++ /dev/null @@ -1,73 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -try: - from ._models_py3 import AzureEntityResource - from ._models_py3 import ComplianceStatus - from ._models_py3 import ErrorDefinition - from ._models_py3 import ErrorResponse, ErrorResponseException - from ._models_py3 import HelmOperatorProperties - from ._models_py3 import ProxyResource - from ._models_py3 import Resource - from ._models_py3 import ResourceProviderOperation - from ._models_py3 import ResourceProviderOperationDisplay - from ._models_py3 import Result - from ._models_py3 import SourceControlConfiguration - from ._models_py3 import SystemData - from ._models_py3 import TrackedResource -except (SyntaxError, ImportError): - from ._models import AzureEntityResource - from ._models import ComplianceStatus - from ._models import ErrorDefinition - from ._models import ErrorResponse, ErrorResponseException - from ._models import HelmOperatorProperties - from ._models import ProxyResource - from ._models import Resource - from ._models import ResourceProviderOperation - from ._models import ResourceProviderOperationDisplay - from ._models import Result - from ._models import SourceControlConfiguration - from ._models import SystemData - from ._models import TrackedResource -from ._paged_models import ResourceProviderOperationPaged -from ._paged_models import SourceControlConfigurationPaged -from ._source_control_configuration_client_enums import ( - ComplianceStateType, - MessageLevelType, - OperatorType, - OperatorScopeType, - ProvisioningStateType, - CreatedByType, -) - -__all__ = [ - 'AzureEntityResource', - 'ComplianceStatus', - 'ErrorDefinition', - 'ErrorResponse', 'ErrorResponseException', - 'HelmOperatorProperties', - 'ProxyResource', - 'Resource', - 'ResourceProviderOperation', - 'ResourceProviderOperationDisplay', - 'Result', - 'SourceControlConfiguration', - 'SystemData', - 'TrackedResource', - 'SourceControlConfigurationPaged', - 'ResourceProviderOperationPaged', - 'ComplianceStateType', - 'MessageLevelType', - 'OperatorType', - 'OperatorScopeType', - 'ProvisioningStateType', - 'CreatedByType', -] diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models.py deleted file mode 100644 index 676504953e7..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models.py +++ /dev/null @@ -1,527 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model -from msrest.exceptions import HttpOperationError - - -class Resource(Model): - """Resource. - - 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. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class AzureEntityResource(Resource): - """Entity Resource. - - The resource model definition for an Azure Resource Manager resource with - an etag. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 etag: Resource Etag. - :vartype etag: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(AzureEntityResource, self).__init__(**kwargs) - self.etag = None - - -class CloudError(Model): - """CloudError. - """ - - _attribute_map = { - } - - -class ComplianceStatus(Model): - """Compliance Status details. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :ivar compliance_state: The compliance state of the configuration. - Possible values include: 'Pending', 'Compliant', 'Noncompliant', - 'Installed', 'Failed' - :vartype compliance_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ComplianceStateType - :param last_config_applied: Datetime the configuration was last applied. - :type last_config_applied: datetime - :param message: Message from when the configuration was applied. - :type message: str - :param message_level: Level of the message. Possible values include: - 'Error', 'Warning', 'Information' - :type message_level: str or - ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType - """ - - _validation = { - 'compliance_state': {'readonly': True}, - } - - _attribute_map = { - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, - 'message': {'key': 'message', 'type': 'str'}, - 'message_level': {'key': 'messageLevel', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(ComplianceStatus, self).__init__(**kwargs) - self.compliance_state = None - self.last_config_applied = kwargs.get('last_config_applied', None) - self.message = kwargs.get('message', None) - self.message_level = kwargs.get('message_level', None) - - -class ErrorDefinition(Model): - """Error definition. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Service specific error code which serves as the - substatus for the HTTP error code. - :type code: str - :param message: Required. Description of the error. - :type message: str - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(ErrorDefinition, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - - -class ErrorResponse(Model): - """Error response. - - :param error: Error definition. - :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDefinition - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinition'}, - } - - def __init__(self, **kwargs): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ErrorResponseException(HttpOperationError): - """Server responsed with exception of type: 'ErrorResponse'. - - :param deserialize: A deserializer - :param response: Server response to be deserialized. - """ - - def __init__(self, deserialize, response, *args): - - super(ErrorResponseException, self).__init__(deserialize, response, 'ErrorResponse', *args) - - -class HelmOperatorProperties(Model): - """Properties for Helm operator. - - :param chart_version: Version of the operator Helm chart. - :type chart_version: str - :param chart_values: Values override for the operator Helm chart. - :type chart_values: str - """ - - _attribute_map = { - 'chart_version': {'key': 'chartVersion', 'type': 'str'}, - 'chart_values': {'key': 'chartValues', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(HelmOperatorProperties, self).__init__(**kwargs) - self.chart_version = kwargs.get('chart_version', None) - self.chart_values = kwargs.get('chart_values', None) - - -class ProxyResource(Resource): - """Proxy 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. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(ProxyResource, self).__init__(**kwargs) - - -class ResourceProviderOperation(Model): - """Supported operation of this resource provider. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :param name: Operation name, in format of - {provider}/{resource}/{operation} - :type name: str - :param display: Display metadata associated with the operation. - :type display: - ~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationDisplay - :ivar is_data_action: The flag that indicates whether the operation - applies to data plane. - :vartype is_data_action: bool - """ - - _validation = { - 'is_data_action': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - } - - def __init__(self, **kwargs): - super(ResourceProviderOperation, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.display = kwargs.get('display', None) - self.is_data_action = None - - -class ResourceProviderOperationDisplay(Model): - """Display metadata associated with the operation. - - :param provider: Resource provider: Microsoft KubernetesConfiguration. - :type provider: str - :param resource: Resource on which the operation is performed. - :type resource: str - :param operation: Type of operation: get, read, delete, etc. - :type operation: str - :param description: Description of this operation. - :type description: str - """ - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(ResourceProviderOperationDisplay, self).__init__(**kwargs) - self.provider = kwargs.get('provider', None) - self.resource = kwargs.get('resource', None) - self.operation = kwargs.get('operation', None) - self.description = kwargs.get('description', None) - - -class Result(Model): - """Sample result definition. - - :param sample_property: Sample property of type string - :type sample_property: str - """ - - _attribute_map = { - 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(Result, self).__init__(**kwargs) - self.sample_property = kwargs.get('sample_property', None) - - -class SourceControlConfiguration(ProxyResource): - """The SourceControl Configuration object returned in Get & Put response. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - :param repository_url: Url of the SourceControl Repository. - :type repository_url: str - :param operator_namespace: The namespace to which this operator is - installed to. Maximum of 253 lower case alphanumeric characters, hyphen - and period only. Default value: "default" . - :type operator_namespace: str - :param operator_instance_name: Instance name of the operator - identifying - the specific configuration. - :type operator_instance_name: str - :param operator_type: Type of the operator. Possible values include: - 'Flux' - :type operator_type: str or - ~azure.mgmt.kubernetesconfiguration.models.OperatorType - :param operator_params: Any Parameters for the Operator instance in string - format. - :type operator_params: str - :param configuration_protected_settings: Name-value pairs of protected - configuration settings for the configuration - :type configuration_protected_settings: dict[str, str] - :param operator_scope: Scope at which the operator will be installed. - Possible values include: 'cluster', 'namespace'. Default value: "cluster" - . - :type operator_scope: str or - ~azure.mgmt.kubernetesconfiguration.models.OperatorScopeType - :ivar repository_public_key: Public Key associated with this SourceControl - configuration (either generated within the cluster or provided by the - user). - :vartype repository_public_key: str - :param ssh_known_hosts_contents: Base64-encoded known_hosts contents - containing public SSH keys required to access private Git instances - :type ssh_known_hosts_contents: str - :param enable_helm_operator: Option to enable Helm Operator for this git - configuration. - :type enable_helm_operator: bool - :param helm_operator_properties: Properties for Helm operator. - :type helm_operator_properties: - ~azure.mgmt.kubernetesconfiguration.models.HelmOperatorProperties - :ivar provisioning_state: The provisioning state of the resource provider. - Possible values include: 'Accepted', 'Deleting', 'Running', 'Succeeded', - 'Failed' - :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningStateType - :ivar compliance_status: Compliance Status of the Configuration - :vartype compliance_status: - ~azure.mgmt.kubernetesconfiguration.models.ComplianceStatus - :param system_data: Top level metadata - https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources - :type system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'repository_public_key': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'compliance_status': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, - 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, - 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, - 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, - 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, - 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, - 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, - 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, - 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, - 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, - 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - } - - def __init__(self, **kwargs): - super(SourceControlConfiguration, self).__init__(**kwargs) - self.repository_url = kwargs.get('repository_url', None) - self.operator_namespace = kwargs.get('operator_namespace', "default") - self.operator_instance_name = kwargs.get('operator_instance_name', None) - self.operator_type = kwargs.get('operator_type', None) - self.operator_params = kwargs.get('operator_params', None) - self.configuration_protected_settings = kwargs.get('configuration_protected_settings', None) - self.operator_scope = kwargs.get('operator_scope', "cluster") - self.repository_public_key = None - self.ssh_known_hosts_contents = kwargs.get('ssh_known_hosts_contents', None) - self.enable_helm_operator = kwargs.get('enable_helm_operator', None) - self.helm_operator_properties = kwargs.get('helm_operator_properties', None) - self.provisioning_state = None - self.compliance_status = None - self.system_data = kwargs.get('system_data', None) - - -class SystemData(Model): - """Metadata pertaining to creation and last modification of the resource. - - :param created_by: The identity that created the resource. - :type created_by: str - :param created_by_type: The type of identity that created the resource. - Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' - :type created_by_type: str or - ~azure.mgmt.kubernetesconfiguration.models.CreatedByType - :param created_at: The timestamp of resource creation (UTC). - :type created_at: datetime - :param last_modified_by: The identity that last modified the resource. - :type last_modified_by: str - :param last_modified_by_type: The type of identity that last modified the - resource. Possible values include: 'User', 'Application', - 'ManagedIdentity', 'Key' - :type last_modified_by_type: str or - ~azure.mgmt.kubernetesconfiguration.models.CreatedByType - :param last_modified_at: The type of identity that last modified the - resource. - :type last_modified_at: 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, **kwargs): - super(SystemData, self).__init__(**kwargs) - self.created_by = kwargs.get('created_by', None) - self.created_by_type = kwargs.get('created_by_type', None) - self.created_at = kwargs.get('created_at', None) - self.last_modified_by = kwargs.get('last_modified_by', None) - self.last_modified_by_type = kwargs.get('last_modified_by_type', None) - self.last_modified_at = kwargs.get('last_modified_at', None) - - -class TrackedResource(Resource): - """Tracked 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 Azure. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - :param tags: Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives - :type location: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - } - - def __init__(self, **kwargs): - super(TrackedResource, self).__init__(**kwargs) - self.tags = kwargs.get('tags', None) - self.location = kwargs.get('location', None) diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models_py3.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models_py3.py deleted file mode 100644 index b77227e4d97..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models_py3.py +++ /dev/null @@ -1,527 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.serialization import Model -from msrest.exceptions import HttpOperationError - - -class Resource(Model): - """Resource. - - 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. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__(self, **kwargs) -> None: - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class AzureEntityResource(Resource): - """Entity Resource. - - The resource model definition for an Azure Resource Manager resource with - an etag. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 etag: Resource Etag. - :vartype etag: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - } - - def __init__(self, **kwargs) -> None: - super(AzureEntityResource, self).__init__(**kwargs) - self.etag = None - - -class CloudError(Model): - """CloudError. - """ - - _attribute_map = { - } - - -class ComplianceStatus(Model): - """Compliance Status details. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :ivar compliance_state: The compliance state of the configuration. - Possible values include: 'Pending', 'Compliant', 'Noncompliant', - 'Installed', 'Failed' - :vartype compliance_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ComplianceStateType - :param last_config_applied: Datetime the configuration was last applied. - :type last_config_applied: datetime - :param message: Message from when the configuration was applied. - :type message: str - :param message_level: Level of the message. Possible values include: - 'Error', 'Warning', 'Information' - :type message_level: str or - ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType - """ - - _validation = { - 'compliance_state': {'readonly': True}, - } - - _attribute_map = { - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'last_config_applied': {'key': 'lastConfigApplied', 'type': 'iso-8601'}, - 'message': {'key': 'message', 'type': 'str'}, - 'message_level': {'key': 'messageLevel', 'type': 'str'}, - } - - def __init__(self, *, last_config_applied=None, message: str=None, message_level=None, **kwargs) -> None: - super(ComplianceStatus, self).__init__(**kwargs) - self.compliance_state = None - self.last_config_applied = last_config_applied - self.message = message - self.message_level = message_level - - -class ErrorDefinition(Model): - """Error definition. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Service specific error code which serves as the - substatus for the HTTP error code. - :type code: str - :param message: Required. Description of the error. - :type message: str - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__(self, *, code: str, message: str, **kwargs) -> None: - super(ErrorDefinition, self).__init__(**kwargs) - self.code = code - self.message = message - - -class ErrorResponse(Model): - """Error response. - - :param error: Error definition. - :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDefinition - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinition'}, - } - - def __init__(self, *, error=None, **kwargs) -> None: - super(ErrorResponse, self).__init__(**kwargs) - self.error = error - - -class ErrorResponseException(HttpOperationError): - """Server responsed with exception of type: 'ErrorResponse'. - - :param deserialize: A deserializer - :param response: Server response to be deserialized. - """ - - def __init__(self, deserialize, response, *args): - - super(ErrorResponseException, self).__init__(deserialize, response, 'ErrorResponse', *args) - - -class HelmOperatorProperties(Model): - """Properties for Helm operator. - - :param chart_version: Version of the operator Helm chart. - :type chart_version: str - :param chart_values: Values override for the operator Helm chart. - :type chart_values: str - """ - - _attribute_map = { - 'chart_version': {'key': 'chartVersion', 'type': 'str'}, - 'chart_values': {'key': 'chartValues', 'type': 'str'}, - } - - def __init__(self, *, chart_version: str=None, chart_values: str=None, **kwargs) -> None: - super(HelmOperatorProperties, self).__init__(**kwargs) - self.chart_version = chart_version - self.chart_values = chart_values - - -class ProxyResource(Resource): - """Proxy 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. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__(self, **kwargs) -> None: - super(ProxyResource, self).__init__(**kwargs) - - -class ResourceProviderOperation(Model): - """Supported operation of this resource provider. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :param name: Operation name, in format of - {provider}/{resource}/{operation} - :type name: str - :param display: Display metadata associated with the operation. - :type display: - ~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationDisplay - :ivar is_data_action: The flag that indicates whether the operation - applies to data plane. - :vartype is_data_action: bool - """ - - _validation = { - 'is_data_action': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - } - - def __init__(self, *, name: str=None, display=None, **kwargs) -> None: - super(ResourceProviderOperation, self).__init__(**kwargs) - self.name = name - self.display = display - self.is_data_action = None - - -class ResourceProviderOperationDisplay(Model): - """Display metadata associated with the operation. - - :param provider: Resource provider: Microsoft KubernetesConfiguration. - :type provider: str - :param resource: Resource on which the operation is performed. - :type resource: str - :param operation: Type of operation: get, read, delete, etc. - :type operation: str - :param description: Description of this operation. - :type description: str - """ - - _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, *, provider: str=None, resource: str=None, operation: str=None, description: str=None, **kwargs) -> None: - super(ResourceProviderOperationDisplay, self).__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - self.description = description - - -class Result(Model): - """Sample result definition. - - :param sample_property: Sample property of type string - :type sample_property: str - """ - - _attribute_map = { - 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, - } - - def __init__(self, *, sample_property: str=None, **kwargs) -> None: - super(Result, self).__init__(**kwargs) - self.sample_property = sample_property - - -class SourceControlConfiguration(ProxyResource): - """The SourceControl Configuration object returned in Get & Put response. - - Variables are only populated by the server, and will be ignored when - sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - :param repository_url: Url of the SourceControl Repository. - :type repository_url: str - :param operator_namespace: The namespace to which this operator is - installed to. Maximum of 253 lower case alphanumeric characters, hyphen - and period only. Default value: "default" . - :type operator_namespace: str - :param operator_instance_name: Instance name of the operator - identifying - the specific configuration. - :type operator_instance_name: str - :param operator_type: Type of the operator. Possible values include: - 'Flux' - :type operator_type: str or - ~azure.mgmt.kubernetesconfiguration.models.OperatorType - :param operator_params: Any Parameters for the Operator instance in string - format. - :type operator_params: str - :param configuration_protected_settings: Name-value pairs of protected - configuration settings for the configuration - :type configuration_protected_settings: dict[str, str] - :param operator_scope: Scope at which the operator will be installed. - Possible values include: 'cluster', 'namespace'. Default value: "cluster" - . - :type operator_scope: str or - ~azure.mgmt.kubernetesconfiguration.models.OperatorScopeType - :ivar repository_public_key: Public Key associated with this SourceControl - configuration (either generated within the cluster or provided by the - user). - :vartype repository_public_key: str - :param ssh_known_hosts_contents: Base64-encoded known_hosts contents - containing public SSH keys required to access private Git instances - :type ssh_known_hosts_contents: str - :param enable_helm_operator: Option to enable Helm Operator for this git - configuration. - :type enable_helm_operator: bool - :param helm_operator_properties: Properties for Helm operator. - :type helm_operator_properties: - ~azure.mgmt.kubernetesconfiguration.models.HelmOperatorProperties - :ivar provisioning_state: The provisioning state of the resource provider. - Possible values include: 'Accepted', 'Deleting', 'Running', 'Succeeded', - 'Failed' - :vartype provisioning_state: str or - ~azure.mgmt.kubernetesconfiguration.models.ProvisioningStateType - :ivar compliance_status: Compliance Status of the Configuration - :vartype compliance_status: - ~azure.mgmt.kubernetesconfiguration.models.ComplianceStatus - :param system_data: Top level metadata - https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources - :type system_data: ~azure.mgmt.kubernetesconfiguration.models.SystemData - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'repository_public_key': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'compliance_status': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'repository_url': {'key': 'properties.repositoryUrl', 'type': 'str'}, - 'operator_namespace': {'key': 'properties.operatorNamespace', 'type': 'str'}, - 'operator_instance_name': {'key': 'properties.operatorInstanceName', 'type': 'str'}, - 'operator_type': {'key': 'properties.operatorType', 'type': 'str'}, - 'operator_params': {'key': 'properties.operatorParams', 'type': 'str'}, - 'configuration_protected_settings': {'key': 'properties.configurationProtectedSettings', 'type': '{str}'}, - 'operator_scope': {'key': 'properties.operatorScope', 'type': 'str'}, - 'repository_public_key': {'key': 'properties.repositoryPublicKey', 'type': 'str'}, - 'ssh_known_hosts_contents': {'key': 'properties.sshKnownHostsContents', 'type': 'str'}, - 'enable_helm_operator': {'key': 'properties.enableHelmOperator', 'type': 'bool'}, - 'helm_operator_properties': {'key': 'properties.helmOperatorProperties', 'type': 'HelmOperatorProperties'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'compliance_status': {'key': 'properties.complianceStatus', 'type': 'ComplianceStatus'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - } - - def __init__(self, *, repository_url: str=None, operator_namespace: str="default", operator_instance_name: str=None, operator_type=None, operator_params: str=None, configuration_protected_settings=None, operator_scope="cluster", ssh_known_hosts_contents: str=None, enable_helm_operator: bool=None, helm_operator_properties=None, system_data=None, **kwargs) -> None: - super(SourceControlConfiguration, self).__init__(**kwargs) - self.repository_url = repository_url - self.operator_namespace = operator_namespace - self.operator_instance_name = operator_instance_name - self.operator_type = operator_type - self.operator_params = operator_params - self.configuration_protected_settings = configuration_protected_settings - self.operator_scope = operator_scope - self.repository_public_key = None - self.ssh_known_hosts_contents = ssh_known_hosts_contents - self.enable_helm_operator = enable_helm_operator - self.helm_operator_properties = helm_operator_properties - self.provisioning_state = None - self.compliance_status = None - self.system_data = system_data - - -class SystemData(Model): - """Metadata pertaining to creation and last modification of the resource. - - :param created_by: The identity that created the resource. - :type created_by: str - :param created_by_type: The type of identity that created the resource. - Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' - :type created_by_type: str or - ~azure.mgmt.kubernetesconfiguration.models.CreatedByType - :param created_at: The timestamp of resource creation (UTC). - :type created_at: datetime - :param last_modified_by: The identity that last modified the resource. - :type last_modified_by: str - :param last_modified_by_type: The type of identity that last modified the - resource. Possible values include: 'User', 'Application', - 'ManagedIdentity', 'Key' - :type last_modified_by_type: str or - ~azure.mgmt.kubernetesconfiguration.models.CreatedByType - :param last_modified_at: The type of identity that last modified the - resource. - :type last_modified_at: 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: str=None, created_by_type=None, created_at=None, last_modified_by: str=None, last_modified_by_type=None, last_modified_at=None, **kwargs) -> None: - super(SystemData, self).__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 TrackedResource(Resource): - """Tracked 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 Azure. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - :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 - :param tags: Resource tags. - :type tags: dict[str, str] - :param location: Required. The geo-location where the resource lives - :type location: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - } - - def __init__(self, *, location: str, tags=None, **kwargs) -> None: - super(TrackedResource, self).__init__(**kwargs) - self.tags = tags - self.location = location diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_paged_models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_paged_models.py deleted file mode 100644 index da03391d8d6..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_paged_models.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from msrest.paging import Paged - - -class SourceControlConfigurationPaged(Paged): - """ - A paging container for iterating over a list of :class:`SourceControlConfiguration ` object - """ - - _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'current_page': {'key': 'value', 'type': '[SourceControlConfiguration]'} - } - - def __init__(self, *args, **kwargs): - - super(SourceControlConfigurationPaged, self).__init__(*args, **kwargs) -class ResourceProviderOperationPaged(Paged): - """ - A paging container for iterating over a list of :class:`ResourceProviderOperation ` object - """ - - _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'current_page': {'key': 'value', 'type': '[ResourceProviderOperation]'} - } - - def __init__(self, *args, **kwargs): - - super(ResourceProviderOperationPaged, self).__init__(*args, **kwargs) diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_source_control_configuration_client_enums.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_source_control_configuration_client_enums.py deleted file mode 100644 index 6708ac68cde..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_source_control_configuration_client_enums.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum - - -class ComplianceStateType(str, Enum): - - pending = "Pending" - compliant = "Compliant" - noncompliant = "Noncompliant" - installed = "Installed" - failed = "Failed" - - -class MessageLevelType(str, Enum): - - error = "Error" - warning = "Warning" - information = "Information" - - -class OperatorType(str, Enum): - - flux = "Flux" - - -class OperatorScopeType(str, Enum): - - cluster = "cluster" - namespace = "namespace" - - -class ProvisioningStateType(str, Enum): - - accepted = "Accepted" - deleting = "Deleting" - running = "Running" - succeeded = "Succeeded" - failed = "Failed" - - -class CreatedByType(str, Enum): - - user = "User" - application = "Application" - managed_identity = "ManagedIdentity" - key = "Key" diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py deleted file mode 100644 index b6c0858d9a7..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -from ._source_control_configurations_operations import SourceControlConfigurationsOperations -from ._operations import Operations - -__all__ = [ - 'SourceControlConfigurationsOperations', - 'Operations', -] diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_operations.py deleted file mode 100644 index 5308b8f8270..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_operations.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -import uuid -from msrest.pipeline import ClientRawResponse - -from .. import models - - -class Operations(object): - """Operations operations. - - You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: The API version to be used with the HTTP request. Constant value: "2021-03-01". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self.api_version = "2021-03-01" - - self.config = config - - def list( - self, custom_headers=None, raw=False, **operation_config): - """List all the available operations the KubernetesConfiguration resource - provider supports. - - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: An iterator like instance of ResourceProviderOperation - :rtype: - ~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperationPaged[~azure.mgmt.kubernetesconfiguration.models.ResourceProviderOperation] - :raises: - :class:`ErrorResponseException` - """ - def prepare_request(next_link=None): - if not next_link: - # Construct URL - url = self.list.metadata['url'] - - # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') - - else: - url = next_link - query_parameters = {} - - # Construct headers - header_parameters = {} - header_parameters['Accept'] = 'application/json' - if self.config.generate_client_request_id: - header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) - if custom_headers: - header_parameters.update(custom_headers) - if self.config.accept_language is not None: - header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - return request - - def internal_paging(next_link=None): - request = prepare_request(next_link) - - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise models.ErrorResponseException(self._deserialize, response) - - return response - - # Deserialize response - header_dict = None - if raw: - header_dict = {} - deserialized = models.ResourceProviderOperationPaged(internal_paging, self._deserialize.dependencies, header_dict) - - return deserialized - list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_source_control_configurations_operations.py deleted file mode 100644 index 4b4a8599262..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_source_control_configurations_operations.py +++ /dev/null @@ -1,386 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -import uuid -from msrest.pipeline import ClientRawResponse -from msrest.polling import LROPoller, NoPolling -from msrestazure.polling.arm_polling import ARMPolling - -from .. import models - - -class SourceControlConfigurationsOperations(object): - """SourceControlConfigurationsOperations operations. - - You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. - - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - :ivar api_version: The API version to be used with the HTTP request. Constant value: "2021-03-01". - """ - - models = models - - def __init__(self, client, config, serializer, deserializer): - - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self.api_version = "2021-03-01" - - self.config = config - - def get( - self, resource_group_name, cluster_rp, cluster_resource_name, cluster_name, source_control_configuration_name, custom_headers=None, raw=False, **operation_config): - """Gets details of the Source Control Configuration. - - :param resource_group_name: The name of the resource group. - :type resource_group_name: str - :param cluster_rp: The Kubernetes cluster RP - either - Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes - (for OnPrem K8S clusters). Possible values include: - 'Microsoft.ContainerService', 'Microsoft.Kubernetes' - :type cluster_rp: str - :param cluster_resource_name: The Kubernetes cluster resource name - - either managedClusters (for AKS clusters) or connectedClusters (for - OnPrem K8S clusters). Possible values include: 'managedClusters', - 'connectedClusters' - :type cluster_resource_name: str - :param cluster_name: The name of the kubernetes cluster. - :type cluster_name: str - :param source_control_configuration_name: Name of the Source Control - Configuration. - :type source_control_configuration_name: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: SourceControlConfiguration or ClientRawResponse if raw=true - :rtype: - ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration - or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`ErrorResponseException` - """ - # Construct URL - url = self.get.metadata['url'] - path_format_arguments = { - 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), - 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), - 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), - 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str') - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') - - # Construct headers - header_parameters = {} - header_parameters['Accept'] = 'application/json' - if self.config.generate_client_request_id: - header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) - if custom_headers: - header_parameters.update(custom_headers) - if self.config.accept_language is not None: - header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise models.ErrorResponseException(self._deserialize, response) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize('SourceControlConfiguration', response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} - - def create_or_update( - self, resource_group_name, cluster_rp, cluster_resource_name, cluster_name, source_control_configuration_name, source_control_configuration, custom_headers=None, raw=False, **operation_config): - """Create a new Kubernetes Source Control Configuration. - - :param resource_group_name: The name of the resource group. - :type resource_group_name: str - :param cluster_rp: The Kubernetes cluster RP - either - Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes - (for OnPrem K8S clusters). Possible values include: - 'Microsoft.ContainerService', 'Microsoft.Kubernetes' - :type cluster_rp: str - :param cluster_resource_name: The Kubernetes cluster resource name - - either managedClusters (for AKS clusters) or connectedClusters (for - OnPrem K8S clusters). Possible values include: 'managedClusters', - 'connectedClusters' - :type cluster_resource_name: str - :param cluster_name: The name of the kubernetes cluster. - :type cluster_name: str - :param source_control_configuration_name: Name of the Source Control - Configuration. - :type source_control_configuration_name: str - :param source_control_configuration: Properties necessary to Create - KubernetesConfiguration. - :type source_control_configuration: - ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: SourceControlConfiguration or ClientRawResponse if raw=true - :rtype: - ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration - or ~msrest.pipeline.ClientRawResponse - :raises: - :class:`ErrorResponseException` - """ - # Construct URL - url = self.create_or_update.metadata['url'] - path_format_arguments = { - 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), - 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), - 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), - 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str') - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') - - # Construct headers - header_parameters = {} - header_parameters['Accept'] = 'application/json' - header_parameters['Content-Type'] = 'application/json; charset=utf-8' - if self.config.generate_client_request_id: - header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) - if custom_headers: - header_parameters.update(custom_headers) - if self.config.accept_language is not None: - header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') - - # Construct body - body_content = self._serialize.body(source_control_configuration, 'SourceControlConfiguration') - - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200, 201]: - raise models.ErrorResponseException(self._deserialize, response) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize('SourceControlConfiguration', response) - if response.status_code == 201: - deserialized = self._deserialize('SourceControlConfiguration', response) - - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_response - - return deserialized - create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} - - - def _delete_initial( - self, resource_group_name, cluster_rp, cluster_resource_name, cluster_name, source_control_configuration_name, custom_headers=None, raw=False, **operation_config): - # Construct URL - url = self.delete.metadata['url'] - path_format_arguments = { - 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), - 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), - 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), - 'sourceControlConfigurationName': self._serialize.url("source_control_configuration_name", source_control_configuration_name, 'str') - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') - - # Construct headers - header_parameters = {} - if self.config.generate_client_request_id: - header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) - if custom_headers: - header_parameters.update(custom_headers) - if self.config.accept_language is not None: - header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') - - # Construct and send request - request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200, 204]: - raise models.ErrorResponseException(self._deserialize, response) - - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - def delete( - self, resource_group_name, cluster_rp, cluster_resource_name, cluster_name, source_control_configuration_name, custom_headers=None, raw=False, polling=True, **operation_config): - """This will delete the YAML file used to set up the Source control - configuration, thus stopping future sync from the source repo. - - :param resource_group_name: The name of the resource group. - :type resource_group_name: str - :param cluster_rp: The Kubernetes cluster RP - either - Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes - (for OnPrem K8S clusters). Possible values include: - 'Microsoft.ContainerService', 'Microsoft.Kubernetes' - :type cluster_rp: str - :param cluster_resource_name: The Kubernetes cluster resource name - - either managedClusters (for AKS clusters) or connectedClusters (for - OnPrem K8S clusters). Possible values include: 'managedClusters', - 'connectedClusters' - :type cluster_resource_name: str - :param cluster_name: The name of the kubernetes cluster. - :type cluster_name: str - :param source_control_configuration_name: Name of the Source Control - Configuration. - :type source_control_configuration_name: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: The poller return type is ClientRawResponse, the - direct response alongside the deserialized response - :param polling: True for ARMPolling, False for no polling, or a - polling object for personal polling strategy - :return: An instance of LROPoller that returns None or - ClientRawResponse if raw==True - :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or - ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]] - :raises: - :class:`ErrorResponseException` - """ - raw_result = self._delete_initial( - resource_group_name=resource_group_name, - cluster_rp=cluster_rp, - cluster_resource_name=cluster_resource_name, - cluster_name=cluster_name, - source_control_configuration_name=source_control_configuration_name, - custom_headers=custom_headers, - raw=True, - **operation_config - ) - - def get_long_running_output(response): - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response - - lro_delay = operation_config.get( - 'long_running_operation_timeout', - self.config.long_running_operation_timeout) - if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'} - - def list( - self, resource_group_name, cluster_rp, cluster_resource_name, cluster_name, custom_headers=None, raw=False, **operation_config): - """List all Source Control Configurations. - - :param resource_group_name: The name of the resource group. - :type resource_group_name: str - :param cluster_rp: The Kubernetes cluster RP - either - Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes - (for OnPrem K8S clusters). Possible values include: - 'Microsoft.ContainerService', 'Microsoft.Kubernetes' - :type cluster_rp: str - :param cluster_resource_name: The Kubernetes cluster resource name - - either managedClusters (for AKS clusters) or connectedClusters (for - OnPrem K8S clusters). Possible values include: 'managedClusters', - 'connectedClusters' - :type cluster_resource_name: str - :param cluster_name: The name of the kubernetes cluster. - :type cluster_name: str - :param dict custom_headers: headers that will be added to the request - :param bool raw: returns the direct response alongside the - deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. - :return: An iterator like instance of SourceControlConfiguration - :rtype: - ~azure.mgmt.kubernetesconfiguration.models.SourceControlConfigurationPaged[~azure.mgmt.kubernetesconfiguration.models.SourceControlConfiguration] - :raises: - :class:`ErrorResponseException` - """ - def prepare_request(next_link=None): - if not next_link: - # Construct URL - url = self.list.metadata['url'] - path_format_arguments = { - 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'), - 'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'), - 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str') - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') - - else: - url = next_link - query_parameters = {} - - # Construct headers - header_parameters = {} - header_parameters['Accept'] = 'application/json' - if self.config.generate_client_request_id: - header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) - if custom_headers: - header_parameters.update(custom_headers) - if self.config.accept_language is not None: - header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') - - # Construct and send request - request = self._client.get(url, query_parameters, header_parameters) - return request - - def internal_paging(next_link=None): - request = prepare_request(next_link) - - response = self._client.send(request, stream=False, **operation_config) - - if response.status_code not in [200]: - raise models.ErrorResponseException(self._deserialize, response) - - return response - - # Deserialize response - header_dict = None - if raw: - header_dict = {} - deserialized = models.SourceControlConfigurationPaged(internal_paging, self._deserialize.dependencies, header_dict) - - return deserialized - list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/_version.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/_version.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/_version.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/_extensions_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/aio/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/_models.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/_models.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/_models_py3.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_models_py3.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/_models_py3.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/models/_source_control_configuration_client_enums.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/_extensions_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_07_01_preview/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/_version.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/_version.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/_version.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/aio/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/_models.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/_models.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models_py3.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/_models_py3.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_models_py3.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/_models_py3.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/models/_source_control_configuration_client_enums.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2020_10_01_preview/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/_version.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/_version.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/_version.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/aio/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/_models.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/_models.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models_py3.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/_models_py3.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_models_py3.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/_models_py3.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/models/_source_control_configuration_client_enums.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_03_01/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/_version.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/_version.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/_version.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_type_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_cluster_extension_types_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_extension_type_versions_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_extensions_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_location_extension_types_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_operation_status_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/aio/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/_models.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/_models.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/_models_py3.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_models_py3.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/_models_py3.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/models/_source_control_configuration_client_enums.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_type_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_cluster_extension_types_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_extension_type_versions_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_extensions_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_location_extension_types_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_operation_status_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_05_01_preview/operations/_source_control_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/_version.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/_version.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/_version.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/_configuration.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_configuration.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/_configuration.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/_source_control_configuration_client.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_config_operation_status_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_flux_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_operation_status_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/aio/operations/_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/_models.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/_models.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models_py3.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/_models_py3.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_models_py3.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/_models_py3.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/models/_source_control_configuration_client_enums.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/__init__.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/__init__.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/__init__.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_flux_config_operation_status_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_flux_configurations_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_operation_status_operations.py diff --git a/src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_operations.py similarity index 100% rename from src/k8s-config/azext_k8s_config/vendored_sdks/v2021_06_01_preview/operations/_operations.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/v2021_06_01_preview/operations/_operations.py diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/version.py deleted file mode 100644 index 9bd1dfac7ec..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/version.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is -# regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.2.0" - diff --git a/src/k8s-configuration/setup.py b/src/k8s-configuration/setup.py index 2701f5bee81..2cc6fc00e58 100644 --- a/src/k8s-configuration/setup.py +++ b/src/k8s-configuration/setup.py @@ -14,9 +14,7 @@ from distutils import log as logger logger.warn("Wheel is not available, disabling bdist_wheel hook") -# TODO: Confirm this is the right version number you want and it matches your -# HISTORY.rst entry. -VERSION = '1.0.1' +VERSION = '1.2.0' # The full list of classifiers is available at # https://pypi.python.org/pypi?%3Aaction=list_classifiers @@ -32,7 +30,6 @@ 'License :: OSI Approved :: MIT License', ] -# TODO: Add any additional SDK dependencies here DEPENDENCIES = ["pycryptodome~=3.9.8"] with open('README.rst', 'r', encoding='utf-8') as f: @@ -54,4 +51,4 @@ packages=find_packages(), install_requires=DEPENDENCIES, package_data={'azext_k8s_configuration': ['azext_metadata.json']}, -) +) \ No newline at end of file From 06b74cfa4f4b385bbab4ed25e104c53b4097c4da Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 7 Sep 2021 13:06:11 -0700 Subject: [PATCH 53/61] Remove extension provider from CLI --- .../partner_extensions/AzureDefender.py | 76 --- .../partner_extensions/AzureMLKubernetes.py | 482 ------------------ .../partner_extensions/Cassandra.py | 61 --- .../partner_extensions/ContainerInsights.py | 458 ----------------- .../partner_extensions/DefaultExtension.py | 61 --- .../DefaultExtensionWithIdentity.py | 53 -- .../partner_extensions/OpenServiceMesh.py | 153 ------ .../PartnerExtensionModel.py | 26 - .../providers/ExtensionProvider.py | 192 ------- .../providers/FluxConfigurationProvider.py | 72 ++- 10 files changed, 62 insertions(+), 1572 deletions(-) delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureDefender.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureMLKubernetes.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/Cassandra.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/ContainerInsights.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtension.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtensionWithIdentity.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/OpenServiceMesh.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/partner_extensions/PartnerExtensionModel.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/providers/ExtensionProvider.py diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureDefender.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureDefender.py deleted file mode 100644 index 61464a2da6d..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureDefender.py +++ /dev/null @@ -1,76 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument - -from knack.log import get_logger - -from ..vendored_sdks.v2021_05_01_preview.models import ( - Extension, - ScopeCluster, - Scope -) - -from .PartnerExtensionModel import PartnerExtensionModel -from .ContainerInsights import _get_container_insights_settings - -logger = get_logger(__name__) - - -class AzureDefender(PartnerExtensionModel): - def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, - scope, auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file): - - """ExtensionType 'microsoft.azuredefender.kubernetes' specific validations & defaults for Create - Must create and return a valid 'ExtensionInstance' object. - - """ - # NOTE-1: Replace default scope creation with your customization! - ext_scope = None - # Hardcoding name, release_namespace and scope since ci only supports one instance and cluster scope - # and platform doesnt have support yet extension specific constraints like this - name = extension_type.lower() - release_namespace = "azuredefender" - # Scope is always cluster - scope_cluster = ScopeCluster(release_namespace=release_namespace) - ext_scope = Scope(cluster=scope_cluster, namespace=None) - - is_ci_extension_type = False - - logger.warning('Ignoring name, release-namespace and scope parameters since %s ' - 'only supports cluster scope and single instance of this extension.', extension_type) - logger.warning("Defaulting to extension name '%s' and release-namespace '%s'", name, release_namespace) - - _get_container_insights_settings(cmd, resource_group_name, cluster_name, configuration_settings, - configuration_protected_settings, is_ci_extension_type) - - # NOTE-2: Return a valid ExtensionInstance object, Instance name and flag for Identity - create_identity = True - extension_instance = Extension( - extension_type=extension_type, - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version, - scope=ext_scope, - configuration_settings=configuration_settings, - configuration_protected_settings=configuration_protected_settings - ) - return extension_instance, name, create_identity - - def Update(self, extension, auto_upgrade_minor_version, release_train, version): - """ExtensionType 'microsoft.azuredefender.kubernetes' specific validations & defaults for Update - Must create and return a valid 'ExtensionInstanceUpdate' object. - - """ - return Extension( - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version - ) - - def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): - pass diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureMLKubernetes.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureMLKubernetes.py deleted file mode 100644 index a0cb1726df4..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/AzureMLKubernetes.py +++ /dev/null @@ -1,482 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument -# pylint: disable=line-too-long -# pylint: disable=too-many-locals - -import copy -from hashlib import md5 -from typing import Any, Dict, List, Tuple - -import azure.mgmt.relay -import azure.mgmt.relay.models -import azure.mgmt.resource.locks -import azure.mgmt.servicebus -import azure.mgmt.servicebus.models -import azure.mgmt.storage -import azure.mgmt.storage.models -import azure.mgmt.loganalytics -import azure.mgmt.loganalytics.models -from azure.cli.core.azclierror import InvalidArgumentValueError, MutuallyExclusiveArgumentError -from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id -from azure.mgmt.resource.locks.models import ManagementLockObject -from knack.log import get_logger -from msrestazure.azure_exceptions import CloudError - -from .._client_factory import cf_resources -from .PartnerExtensionModel import PartnerExtensionModel -from ..vendored_sdks.v2021_05_01_preview.models import ( - Extension, - ScopeCluster, - Scope -) - -logger = get_logger(__name__) - -resource_tag = {'created_by': 'Azure Arc-enabled ML'} - - -# pylint: disable=too-many-instance-attributes -class AzureMLKubernetes(PartnerExtensionModel): - def __init__(self): - # constants for configuration settings. - self.DEFAULT_RELEASE_NAMESPACE = 'azureml' - self.RELAY_CONNECTION_STRING_KEY = 'relayserver.relayConnectionString' - self.RELAY_CONNECTION_STRING_DEPRECATED_KEY = 'RelayConnectionString' # for 3rd party deployment, will be deprecated - self.HC_RESOURCE_ID_KEY = 'relayserver.hybridConnectionResourceID' - self.RELAY_HC_NAME_KEY = 'relayserver.hybridConnectionName' - self.SERVICE_BUS_CONNECTION_STRING_KEY = 'servicebus.connectionString' - self.SERVICE_BUS_RESOURCE_ID_KEY = 'servicebus.resourceID' - self.SERVICE_BUS_TOPIC_SUB_MAPPING_KEY = 'servicebus.topicSubMapping' - self.AZURE_LOG_ANALYTICS_ENABLED_KEY = 'azure_log_analytics.enabled' - self.AZURE_LOG_ANALYTICS_CUSTOMER_ID_KEY = 'azure_log_analytics.customer_id' - self.AZURE_LOG_ANALYTICS_CONNECTION_STRING = 'azure_log_analytics.connection_string' - self.JOB_SCHEDULER_LOCATION_KEY = 'jobSchedulerLocation' - self.CLUSTER_NAME_FRIENDLY_KEY = 'cluster_name_friendly' - - # component flag - self.ENABLE_TRAINING = 'enableTraining' - self.ENABLE_INFERENCE = 'enableInference' - - # constants for determine whether create underlying azure resource - self.RELAY_SERVER_CONNECTION_STRING = 'relayServerConnectionString' # create relay connection string if None - self.SERVICE_BUS_CONNECTION_STRING = 'serviceBusConnectionString' # create service bus if None - self.LOG_ANALYTICS_WS_ENABLED = 'logAnalyticsWS' # create log analytics workspace if true - - # constants for azure resources creation - self.RELAY_HC_AUTH_NAME = 'azureml_rw' - self.SERVICE_BUS_COMPUTE_STATE_TOPIC = 'computestate-updatedby-computeprovider' - self.SERVICE_BUS_COMPUTE_STATE_SUB = 'compute-scheduler-computestate' - self.SERVICE_BUS_JOB_STATE_TOPIC = 'jobstate-updatedby-computeprovider' - self.SERVICE_BUS_JOB_STATE_SUB = 'compute-scheduler-jobstate' - - # constants for enabling SSL in inference - self.sslKeyPemFile = 'sslKeyPemFile' - self.sslCertPemFile = 'sslCertPemFile' - self.allowInsecureConnections = 'allowInsecureConnections' - self.privateEndpointILB = 'privateEndpointILB' - self.privateEndpointNodeport = 'privateEndpointNodeport' - self.inferenceLoadBalancerHA = 'inferenceLoadBalancerHA' - - # reference mapping - self.reference_mapping = { - self.RELAY_SERVER_CONNECTION_STRING: [self.RELAY_CONNECTION_STRING_KEY, self.RELAY_CONNECTION_STRING_DEPRECATED_KEY], - self.SERVICE_BUS_CONNECTION_STRING: [self.SERVICE_BUS_CONNECTION_STRING_KEY], - 'cluster_name': ['clusterId', 'prometheus.prometheusSpec.externalLabels.cluster_name'], - } - - def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, - scope, auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file): - if scope == 'namespace': - raise InvalidArgumentValueError("Invalid scope '{}'. This extension can be installed " - "only at 'cluster' scope.".format(scope)) - if not release_namespace: - release_namespace = self.DEFAULT_RELEASE_NAMESPACE - scope_cluster = ScopeCluster(release_namespace=release_namespace) - ext_scope = Scope(cluster=scope_cluster, namespace=None) - - # validate the config - self.__validate_config(configuration_settings, configuration_protected_settings) - - # get the arc's location - subscription_id = get_subscription_id(cmd.cli_ctx) - cluster_rp, parent_api_version = _get_cluster_rp_api_version(cluster_type) - cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}' \ - '/{3}/{4}'.format(subscription_id, resource_group_name, cluster_rp, cluster_type, cluster_name) - cluster_location = '' - resources = cf_resources(cmd.cli_ctx, subscription_id) - try: - resource = resources.get_by_id( - cluster_resource_id, parent_api_version) - cluster_location = resource.location.lower() - except CloudError as ex: - raise ex - - # generate values for the extension if none is set. - configuration_settings['cluster_name'] = configuration_settings.get('cluster_name', cluster_resource_id) - configuration_settings['domain'] = configuration_settings.get( - 'doamin', '{}.cloudapp.azure.com'.format(cluster_location)) - configuration_settings['location'] = configuration_settings.get('location', cluster_location) - configuration_settings[self.JOB_SCHEDULER_LOCATION_KEY] = configuration_settings.get( - self.JOB_SCHEDULER_LOCATION_KEY, cluster_location) - configuration_settings[self.CLUSTER_NAME_FRIENDLY_KEY] = configuration_settings.get( - self.CLUSTER_NAME_FRIENDLY_KEY, cluster_name) - - # create Azure resources need by the extension based on the config. - self.__create_required_resource( - cmd, configuration_settings, configuration_protected_settings, subscription_id, resource_group_name, - cluster_name, cluster_location) - - # dereference - configuration_settings = _dereference(self.reference_mapping, configuration_settings) - configuration_protected_settings = _dereference(self.reference_mapping, configuration_protected_settings) - - # If release-train is not input, set it to 'stable' - if release_train is None: - release_train = 'stable' - - create_identity = True - extension_instance = Extension( - extension_type=extension_type, - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version, - scope=ext_scope, - configuration_settings=configuration_settings, - configuration_protected_settings=configuration_protected_settings, - identity=None, - location="" - ) - return extension_instance, name, create_identity - - def Update(self, extension, auto_upgrade_minor_version, release_train, version): - return Extension( - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version - ) - - def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): - # Give a warning message - logger.warning("If nvidia.com/gpu or fuse resource is not recognized by kubernetes after this deletion, " - "you probably have installed nvidia-device-plugin or fuse-device-plugin before installing AMLArc extension. " - "Please try to reinstall device plugins to fix this issue.") - - def __validate_config(self, configuration_settings, configuration_protected_settings): - # perform basic validation of the input config - config_keys = configuration_settings.keys() - config_protected_keys = configuration_protected_settings.keys() - dup_keys = set(config_keys) & set(config_protected_keys) - if dup_keys: - for key in dup_keys: - logger.warning( - 'Duplicate keys found in both configuration settings and configuration protected setttings: %s', key) - raise InvalidArgumentValueError("Duplicate keys found.") - - enable_training = _get_value_from_config_protected_config( - self.ENABLE_TRAINING, configuration_settings, configuration_protected_settings) - enable_training = str(enable_training).lower() == 'true' - - enable_inference = _get_value_from_config_protected_config( - self.ENABLE_INFERENCE, configuration_settings, configuration_protected_settings) - enable_inference = str(enable_inference).lower() == 'true' - - if enable_inference: - logger.warning("The installed AzureML extension for AML inference is experimental and not covered by customer support. Please use with discretion.") - self.__validate_scoring_fe_settings(configuration_settings, configuration_protected_settings) - self.__set_up_inference_ssl(configuration_settings, configuration_protected_settings) - elif not (enable_training or enable_inference): - raise InvalidArgumentValueError( - "Please create Microsoft.AzureML.Kubernetes extension instance either " - "for Machine Learning training or inference by specifying " - f"'--configuration-settings {self.ENABLE_TRAINING}=true' or '--configuration-settings {self.ENABLE_INFERENCE}=true'") - - configuration_settings[self.ENABLE_TRAINING] = configuration_settings.get(self.ENABLE_TRAINING, enable_training) - configuration_settings[self.ENABLE_INFERENCE] = configuration_settings.get( - self.ENABLE_INFERENCE, enable_inference) - configuration_protected_settings.pop(self.ENABLE_TRAINING, None) - configuration_protected_settings.pop(self.ENABLE_INFERENCE, None) - - def __validate_scoring_fe_settings(self, configuration_settings, configuration_protected_settings): - isTestCluster = _get_value_from_config_protected_config( - self.inferenceLoadBalancerHA, configuration_settings, configuration_protected_settings) - isTestCluster = str(isTestCluster).lower() == 'false' - if isTestCluster: - configuration_settings['clusterPurpose'] = 'DevTest' - else: - configuration_settings['clusterPurpose'] = 'FastProd' - feSslCertFile = configuration_protected_settings.get(self.sslCertPemFile) - feSslKeyFile = configuration_protected_settings.get(self.sslKeyPemFile) - allowInsecureConnections = _get_value_from_config_protected_config( - self.allowInsecureConnections, configuration_settings, configuration_protected_settings) - allowInsecureConnections = str(allowInsecureConnections).lower() == 'true' - if (not feSslCertFile or not feSslKeyFile) and not allowInsecureConnections: - raise InvalidArgumentValueError( - "Provide ssl certificate and key. " - "Otherwise explicitly allow insecure connection by specifying " - "'--configuration-settings allowInsecureConnections=true'") - - feIsNodePort = _get_value_from_config_protected_config( - self.privateEndpointNodeport, configuration_settings, configuration_protected_settings) - feIsNodePort = str(feIsNodePort).lower() == 'true' - feIsInternalLoadBalancer = _get_value_from_config_protected_config( - self.privateEndpointILB, configuration_settings, configuration_protected_settings) - feIsInternalLoadBalancer = str(feIsInternalLoadBalancer).lower() == 'true' - - if feIsNodePort and feIsInternalLoadBalancer: - raise MutuallyExclusiveArgumentError( - "Specify either privateEndpointNodeport=true or privateEndpointILB=true, but not both.") - if feIsNodePort: - configuration_settings['scoringFe.serviceType.nodePort'] = feIsNodePort - elif feIsInternalLoadBalancer: - configuration_settings['scoringFe.serviceType.internalLoadBalancer'] = feIsInternalLoadBalancer - logger.warning( - 'Internal load balancer only supported on AKS and AKS Engine Clusters.') - - def __set_up_inference_ssl(self, configuration_settings, configuration_protected_settings): - allowInsecureConnections = _get_value_from_config_protected_config( - self.allowInsecureConnections, configuration_settings, configuration_protected_settings) - allowInsecureConnections = str(allowInsecureConnections).lower() == 'true' - if not allowInsecureConnections: - import base64 - feSslCertFile = configuration_protected_settings.get(self.sslCertPemFile) - feSslKeyFile = configuration_protected_settings.get(self.sslKeyPemFile) - with open(feSslCertFile) as f: - cert_data = f.read() - cert_data_bytes = cert_data.encode("ascii") - ssl_cert = base64.b64encode(cert_data_bytes).decode() - configuration_protected_settings['scoringFe.sslCert'] = ssl_cert - with open(feSslKeyFile) as f: - key_data = f.read() - key_data_bytes = key_data.encode("ascii") - ssl_key = base64.b64encode(key_data_bytes).decode() - configuration_protected_settings['scoringFe.sslKey'] = ssl_key - else: - logger.warning( - 'SSL is not enabled. Allowing insecure connections to the deployed services.') - - def __create_required_resource( - self, cmd, configuration_settings, configuration_protected_settings, subscription_id, resource_group_name, - cluster_name, cluster_location): - if str(configuration_settings.get(self.LOG_ANALYTICS_WS_ENABLED, False)).lower() == 'true'\ - and not configuration_settings.get(self.AZURE_LOG_ANALYTICS_CONNECTION_STRING)\ - and not configuration_protected_settings.get(self.AZURE_LOG_ANALYTICS_CONNECTION_STRING): - logger.info('==== BEGIN LOG ANALYTICS WORKSPACE CREATION ====') - ws_costumer_id, shared_key = _get_log_analytics_ws_connection_string( - cmd, subscription_id, resource_group_name, cluster_name, cluster_location) - logger.info('==== END LOG ANALYTICS WORKSPACE CREATION ====') - configuration_settings[self.AZURE_LOG_ANALYTICS_ENABLED_KEY] = True - configuration_settings[self.AZURE_LOG_ANALYTICS_CUSTOMER_ID_KEY] = ws_costumer_id - configuration_protected_settings[self.AZURE_LOG_ANALYTICS_CONNECTION_STRING] = shared_key - - if not configuration_settings.get(self.RELAY_SERVER_CONNECTION_STRING) and \ - not configuration_protected_settings.get(self.RELAY_SERVER_CONNECTION_STRING): - logger.info('==== BEGIN RELAY CREATION ====') - relay_connection_string, hc_resource_id, hc_name = _get_relay_connection_str( - cmd, subscription_id, resource_group_name, cluster_name, cluster_location, self.RELAY_HC_AUTH_NAME) - logger.info('==== END RELAY CREATION ====') - configuration_protected_settings[self.RELAY_SERVER_CONNECTION_STRING] = relay_connection_string - configuration_settings[self.HC_RESOURCE_ID_KEY] = hc_resource_id - configuration_settings[self.RELAY_HC_NAME_KEY] = hc_name - - if not configuration_settings.get(self.SERVICE_BUS_CONNECTION_STRING) and \ - not configuration_protected_settings.get(self.SERVICE_BUS_CONNECTION_STRING): - logger.info('==== BEGIN SERVICE BUS CREATION ====') - topic_sub_mapping = { - self.SERVICE_BUS_COMPUTE_STATE_TOPIC: self.SERVICE_BUS_COMPUTE_STATE_SUB, - self.SERVICE_BUS_JOB_STATE_TOPIC: self.SERVICE_BUS_JOB_STATE_SUB - } - service_bus_connection_string, service_buse_resource_id = _get_service_bus_connection_string( - cmd, subscription_id, resource_group_name, cluster_name, cluster_location, topic_sub_mapping) - logger.info('==== END SERVICE BUS CREATION ====') - configuration_protected_settings[self.SERVICE_BUS_CONNECTION_STRING] = service_bus_connection_string - configuration_settings[self.SERVICE_BUS_RESOURCE_ID_KEY] = service_buse_resource_id - configuration_settings[f'{self.SERVICE_BUS_TOPIC_SUB_MAPPING_KEY}.{self.SERVICE_BUS_COMPUTE_STATE_TOPIC}'] = self.SERVICE_BUS_COMPUTE_STATE_SUB - configuration_settings[f'{self.SERVICE_BUS_TOPIC_SUB_MAPPING_KEY}.{self.SERVICE_BUS_JOB_STATE_TOPIC}'] = self.SERVICE_BUS_JOB_STATE_SUB - - -def _get_valid_name(input_name: str, suffix_len: int, max_len: int) -> str: - normalized_str = ''.join(filter(str.isalnum, input_name)) - assert normalized_str, "normalized name empty" - - if len(normalized_str) <= max_len: - return normalized_str - - if suffix_len > max_len: - logger.warning( - "suffix length is bigger than max length. Set suffix length to max length.") - suffix_len = max_len - - md5_suffix = md5(input_name.encode("utf8")).hexdigest()[:suffix_len] - new_name = normalized_str[:max_len - suffix_len] + md5_suffix - return new_name - - -# pylint: disable=broad-except -def _lock_resource(cmd, lock_scope, lock_level='CanNotDelete'): - lock_client: azure.mgmt.resource.locks.ManagementLockClient = get_mgmt_service_client( - cmd.cli_ctx, azure.mgmt.resource.locks.ManagementLockClient) - # put lock on relay resource - lock_object = ManagementLockObject(level=lock_level, notes='locked by amlarc.') - try: - lock_client.management_locks.create_or_update_by_scope( - scope=lock_scope, lock_name='amlarc-resource-lock', parameters=lock_object) - except Exception: - # try to lock the resource if user has the owner privilege - pass - - -def _get_relay_connection_str( - cmd, subscription_id, resource_group_name, cluster_name, cluster_location, auth_rule_name) -> Tuple[str, str, str]: - relay_client: azure.mgmt.relay.RelayManagementClient = get_mgmt_service_client( - cmd.cli_ctx, azure.mgmt.relay.RelayManagementClient) - - cluster_id = '{}-{}-{}-relay'.format(cluster_name, subscription_id, resource_group_name) - # create namespace - relay_namespace_name = _get_valid_name( - cluster_id, suffix_len=6, max_len=50) - relay_namespace_params = azure.mgmt.relay.models.RelayNamespace( - location=cluster_location, tags=resource_tag) - - async_poller = relay_client.namespaces.create_or_update( - resource_group_name, relay_namespace_name, relay_namespace_params) - while True: - async_poller.result(15) - if async_poller.done(): - break - - # create hybrid connection - hybrid_connection_name = cluster_name - hybrid_connection_object = relay_client.hybrid_connections.create_or_update( - resource_group_name, relay_namespace_name, hybrid_connection_name, requires_client_authorization=True) - - # relay_namespace_ojbect = relay_client.namespaces.get(resource_group_name, relay_namespace_name) - # relay_namespace_resource_id = relay_namespace_ojbect.id - # _lock_resource(cmd, lock_scope=relay_namespace_resource_id) - - # create authorization rule - auth_rule_rights = [azure.mgmt.relay.models.AccessRights.manage, - azure.mgmt.relay.models.AccessRights.send, azure.mgmt.relay.models.AccessRights.listen] - relay_client.hybrid_connections.create_or_update_authorization_rule( - resource_group_name, relay_namespace_name, hybrid_connection_name, auth_rule_name, rights=auth_rule_rights) - - # get connection string - key: azure.mgmt.relay.models.AccessKeys = relay_client.hybrid_connections.list_keys( - resource_group_name, relay_namespace_name, hybrid_connection_name, auth_rule_name) - return f'{key.primary_connection_string}', hybrid_connection_object.id, hybrid_connection_name - - -def _get_service_bus_connection_string(cmd, subscription_id, resource_group_name, cluster_name, cluster_location, - topic_sub_mapping: Dict[str, str]) -> Tuple[str, str]: - service_bus_client: azure.mgmt.servicebus.ServiceBusManagementClient = get_mgmt_service_client( - cmd.cli_ctx, azure.mgmt.servicebus.ServiceBusManagementClient) - cluster_id = '{}-{}-{}-service-bus'.format(cluster_name, - subscription_id, resource_group_name) - service_bus_namespace_name = _get_valid_name( - cluster_id, suffix_len=6, max_len=50) - - # create namespace - service_bus_sku = azure.mgmt.servicebus.models.SBSku( - name=azure.mgmt.servicebus.models.SkuName.standard.name) - service_bus_namespace = azure.mgmt.servicebus.models.SBNamespace( - location=cluster_location, - sku=service_bus_sku, - tags=resource_tag) - async_poller = service_bus_client.namespaces.begin_create_or_update( - resource_group_name, service_bus_namespace_name, service_bus_namespace) - while True: - async_poller.result(15) - if async_poller.done(): - break - - for topic_name, service_bus_subscription_name in topic_sub_mapping.items(): - # create topic - topic = azure.mgmt.servicebus.models.SBTopic(max_size_in_megabytes=5120, default_message_time_to_live='P60D') - service_bus_client.topics.create_or_update( - resource_group_name, service_bus_namespace_name, topic_name, topic) - - # create subscription - sub = azure.mgmt.servicebus.models.SBSubscription( - max_delivery_count=1, default_message_time_to_live='P14D', lock_duration='PT30S') - service_bus_client.subscriptions.create_or_update( - resource_group_name, service_bus_namespace_name, topic_name, service_bus_subscription_name, sub) - - service_bus_object = service_bus_client.namespaces.get(resource_group_name, service_bus_namespace_name) - service_bus_resource_id = service_bus_object.id - # _lock_resource(cmd, service_bus_resource_id) - - # get connection string - auth_rules = service_bus_client.namespaces.list_authorization_rules( - resource_group_name, service_bus_namespace_name) - for rule in auth_rules: - key: azure.mgmt.servicebus.models.AccessKeys = service_bus_client.namespaces.list_keys( - resource_group_name, service_bus_namespace_name, rule.name) - return key.primary_connection_string, service_bus_resource_id - - -def _get_log_analytics_ws_connection_string( - cmd, subscription_id, resource_group_name, cluster_name, cluster_location) -> Tuple[str, str]: - log_analytics_ws_client: azure.mgmt.loganalytics.LogAnalyticsManagementClient = get_mgmt_service_client( - cmd.cli_ctx, azure.mgmt.loganalytics.LogAnalyticsManagementClient) - - # create workspace - cluster_id = '{}-{}-{}'.format(cluster_name, subscription_id, resource_group_name) - log_analytics_ws_name = _get_valid_name(cluster_id, suffix_len=6, max_len=63) - log_analytics_ws = azure.mgmt.loganalytics.models.Workspace(location=cluster_location, tags=resource_tag) - async_poller = log_analytics_ws_client.workspaces.begin_create_or_update( - resource_group_name, log_analytics_ws_name, log_analytics_ws) - customer_id = '' - # log_analytics_ws_resource_id = '' - while True: - log_analytics_ws_object = async_poller.result(15) - if async_poller.done(): - customer_id = log_analytics_ws_object.customer_id - # log_analytics_ws_resource_id = log_analytics_ws_object.id - break - - # _lock_resource(cmd, log_analytics_ws_resource_id) - - # get workspace shared keys - shared_key = log_analytics_ws_client.shared_keys.get_shared_keys( - resource_group_name, log_analytics_ws_name).primary_shared_key - return customer_id, shared_key - - -def _dereference(ref_mapping_dict: Dict[str, List], output_dict: Dict[str, Any]): - output_dict = copy.deepcopy(output_dict) - for ref_key, ref_list in ref_mapping_dict.items(): - if ref_key not in output_dict: - continue - ref_value = output_dict[ref_key] - for key in ref_list: - # if user has set the value, skip. - output_dict[key] = output_dict.get(key, ref_value) - return output_dict - - -def _get_value_from_config_protected_config(key, config, protected_config): - if key in config: - return config[key] - return protected_config.get(key) - - -def _get_cluster_rp_api_version(cluster_type) -> Tuple[str, str]: - rp = '' - parent_api_version = '' - if cluster_type.lower() == 'connectedclusters': - rp = 'Microsoft.Kubernetes' - parent_api_version = '2020-01-01-preview' - elif cluster_type.lower() == 'appliances': - rp = 'Microsoft.ResourceConnector' - parent_api_version = '2020-09-15-privatepreview' - elif cluster_type.lower() == '': - rp = 'Microsoft.ContainerService' - parent_api_version = '2017-07-01' - else: - raise InvalidArgumentValueError("Error! Cluster type '{}' is not supported".format(cluster_type)) - return rp, parent_api_version diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/Cassandra.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/Cassandra.py deleted file mode 100644 index ed3e41891db..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/Cassandra.py +++ /dev/null @@ -1,61 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument - -from ..vendored_sdks.v2021_05_01_preview.models import ( - Extension, - ScopeCluster, - Scope, - ScopeNamespace -) - -from .PartnerExtensionModel import PartnerExtensionModel - - -class Cassandra(PartnerExtensionModel): - def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, - scope, auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file): - - """Default validations & defaults for Create - Must create and return a valid 'Extension' object. - - """ - ext_scope = None - if scope is not None: - if scope.lower() == 'cluster': - scope_cluster = ScopeCluster(release_namespace=release_namespace) - ext_scope = Scope(cluster=scope_cluster, namespace=None) - elif scope.lower() == 'namespace': - scope_namespace = ScopeNamespace(target_namespace=target_namespace) - ext_scope = Scope(namespace=scope_namespace, cluster=None) - - create_identity = True - extension_instance = Extension( - extension_type=extension_type, - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version, - scope=ext_scope, - configuration_settings=configuration_settings, - configuration_protected_settings=configuration_protected_settings, - ) - return extension_instance, name, create_identity - - def Update(self, extension, auto_upgrade_minor_version, release_train, version): - """Default validations & defaults for Update - Must create and return a valid 'Extension' object. - - """ - return Extension( - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version - ) - - def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): - pass diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/ContainerInsights.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/ContainerInsights.py deleted file mode 100644 index e6e6b3c2023..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/ContainerInsights.py +++ /dev/null @@ -1,458 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument - -import datetime -import json - -from knack.log import get_logger - -from azure.cli.core.azclierror import InvalidArgumentValueError -from azure.cli.core.commands import LongRunningOperation -from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id -from azure.cli.core.util import sdk_no_wait -from msrestazure.tools import parse_resource_id, is_valid_resource_id - -from ..vendored_sdks.v2021_05_01_preview.models import ( - Extension, - ScopeCluster, - Scope -) - -from .PartnerExtensionModel import PartnerExtensionModel - -from .._client_factory import ( - cf_resources, cf_resource_groups, cf_log_analytics) - -logger = get_logger(__name__) - - -class ContainerInsights(PartnerExtensionModel): - def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, - scope, auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file): - - """ExtensionType 'microsoft.azuremonitor.containers' specific validations & defaults for Create - Must create and return a valid 'Extension' object. - - """ - # NOTE-1: Replace default scope creation with your customization! - ext_scope = None - # Hardcoding name, release_namespace and scope since container-insights only supports one instance and cluster - # scope and platform doesnt have support yet extension specific constraints like this - name = 'azuremonitor-containers' - release_namespace = 'azuremonitor-containers' - # Scope is always cluster - scope_cluster = ScopeCluster(release_namespace=release_namespace) - ext_scope = Scope(cluster=scope_cluster, namespace=None) - - is_ci_extension_type = True - - logger.warning('Ignoring name, release-namespace and scope parameters since %s ' - 'only supports cluster scope and single instance of this extension.', extension_type) - logger.warning("Defaulting to extension name '%s' and release-namespace '%s'", name, release_namespace) - - _get_container_insights_settings(cmd, resource_group_name, cluster_name, configuration_settings, - configuration_protected_settings, is_ci_extension_type) - - # NOTE-2: Return a valid ExtensionInstance object, Instance name and flag for Identity - create_identity = True - extension_instance = Extension( - extension_type=extension_type, - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version, - scope=ext_scope, - configuration_settings=configuration_settings, - configuration_protected_settings=configuration_protected_settings - ) - return extension_instance, name, create_identity - - def Update(self, extension, auto_upgrade_minor_version, release_train, version): - """ExtensionType 'microsoft.azuremonitor.containers' specific validations & defaults for Update - Must create and return a valid 'Extension' object. - - """ - return Extension( - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version - ) - - def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): - pass - - -# Custom Validation Logic for Container Insights - -def _invoke_deployment(cmd, resource_group_name, deployment_name, template, parameters, validate, no_wait, - subscription_id=None): - from azure.cli.core.profiles import ResourceType - deployment_properties = cmd.get_models('DeploymentProperties', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) - properties = deployment_properties(template=template, parameters=parameters, mode='incremental') - smc = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, - subscription_id=subscription_id).deployments - if validate: - logger.info('==== BEGIN TEMPLATE ====') - logger.info(json.dumps(template, indent=2)) - logger.info('==== END TEMPLATE ====') - - deployment_temp = cmd.get_models('Deployment', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) - deployment = deployment_temp(properties=properties) - if validate: - if cmd.supported_api_version(min_api='2019-10-01', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES): - validation_poller = smc.begin_validate(resource_group_name, deployment_name, deployment) - return LongRunningOperation(cmd.cli_ctx)(validation_poller) - return smc.validate(resource_group_name, deployment_name, deployment) - - return sdk_no_wait(no_wait, smc.begin_create_or_update, resource_group_name, deployment_name, deployment) - - -def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, - cluster_resource_group_name, cluster_name): - # mapping for azure public cloud - # log analytics workspaces cannot be created in WCUS region due to capacity limits - # so mapped to EUS per discussion with log analytics team - # pylint: disable=too-many-locals,too-many-statements - - azurecloud_location_to_oms_region_code_map = { - "australiasoutheast": "ASE", - "australiaeast": "EAU", - "australiacentral": "CAU", - "canadacentral": "CCA", - "centralindia": "CIN", - "centralus": "CUS", - "eastasia": "EA", - "eastus": "EUS", - "eastus2": "EUS2", - "eastus2euap": "EAP", - "francecentral": "PAR", - "japaneast": "EJP", - "koreacentral": "SE", - "northeurope": "NEU", - "southcentralus": "SCUS", - "southeastasia": "SEA", - "uksouth": "SUK", - "usgovvirginia": "USGV", - "westcentralus": "EUS", - "westeurope": "WEU", - "westus": "WUS", - "westus2": "WUS2" - } - azurecloud_region_to_oms_region_map = { - "australiacentral": "australiacentral", - "australiacentral2": "australiacentral", - "australiaeast": "australiaeast", - "australiasoutheast": "australiasoutheast", - "brazilsouth": "southcentralus", - "canadacentral": "canadacentral", - "canadaeast": "canadacentral", - "centralus": "centralus", - "centralindia": "centralindia", - "eastasia": "eastasia", - "eastus": "eastus", - "eastus2": "eastus2", - "francecentral": "francecentral", - "francesouth": "francecentral", - "japaneast": "japaneast", - "japanwest": "japaneast", - "koreacentral": "koreacentral", - "koreasouth": "koreacentral", - "northcentralus": "eastus", - "northeurope": "northeurope", - "southafricanorth": "westeurope", - "southafricawest": "westeurope", - "southcentralus": "southcentralus", - "southeastasia": "southeastasia", - "southindia": "centralindia", - "uksouth": "uksouth", - "ukwest": "uksouth", - "westcentralus": "eastus", - "westeurope": "westeurope", - "westindia": "centralindia", - "westus": "westus", - "westus2": "westus2" - } - - # mapping for azure china cloud - # currently log analytics supported only China East 2 region - azurechina_location_to_oms_region_code_map = { - "chinaeast": "EAST2", - "chinaeast2": "EAST2", - "chinanorth": "EAST2", - "chinanorth2": "EAST2" - } - azurechina_region_to_oms_region_map = { - "chinaeast": "chinaeast2", - "chinaeast2": "chinaeast2", - "chinanorth": "chinaeast2", - "chinanorth2": "chinaeast2" - } - - # mapping for azure us governmner cloud - azurefairfax_location_to_oms_region_code_map = { - "usgovvirginia": "USGV" - } - azurefairfax_region_to_oms_region_map = { - "usgovvirginia": "usgovvirginia" - } - - from azure.core.exceptions import HttpResponseError - from azure.cli.core.profiles import ResourceType - - cluster_location = '' - resources = cf_resources(cmd.cli_ctx, subscription_id) - - cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Kubernetes' \ - '/connectedClusters/{2}'.format(subscription_id, cluster_resource_group_name, cluster_name) - try: - resource = resources.get_by_id(cluster_resource_id, '2020-01-01-preview') - cluster_location = resource.location.lower() - except HttpResponseError as ex: - raise ex - - cloud_name = cmd.cli_ctx.cloud.name.lower() - workspace_region = "eastus" - workspace_region_code = "EUS" - - # sanity check that locations and clouds match. - if ((cloud_name == 'azurecloud' and azurechina_region_to_oms_region_map.get(cluster_location, False)) or - (cloud_name == 'azurecloud' and azurefairfax_region_to_oms_region_map.get(cluster_location, False))): - raise InvalidArgumentValueError( - 'Wrong cloud (azurecloud) setting for region {}, please use "az cloud set ..."' - .format(cluster_location) - ) - - if ((cloud_name == 'azurechinacloud' and azurecloud_region_to_oms_region_map.get(cluster_location, False)) or - (cloud_name == 'azurechinacloud' and azurefairfax_region_to_oms_region_map.get(cluster_location, False))): - raise InvalidArgumentValueError( - 'Wrong cloud (azurechinacloud) setting for region {}, please use "az cloud set ..."' - .format(cluster_location) - ) - - if ((cloud_name == 'azureusgovernment' and azurecloud_region_to_oms_region_map.get(cluster_location, False)) or - (cloud_name == 'azureusgovernment' and azurechina_region_to_oms_region_map.get(cluster_location, False))): - raise InvalidArgumentValueError( - 'Wrong cloud (azureusgovernment) setting for region {}, please use "az cloud set ..."' - .format(cluster_location) - ) - - if cloud_name == 'azurecloud': - workspace_region = azurecloud_region_to_oms_region_map.get(cluster_location, "eastus") - workspace_region_code = azurecloud_location_to_oms_region_code_map.get(workspace_region, "EUS") - elif cloud_name == 'azurechinacloud': - workspace_region = azurechina_region_to_oms_region_map.get(cluster_location, "chinaeast2") - workspace_region_code = azurechina_location_to_oms_region_code_map.get(workspace_region, "EAST2") - elif cloud_name == 'azureusgovernment': - workspace_region = azurefairfax_region_to_oms_region_map.get(cluster_location, "usgovvirginia") - workspace_region_code = azurefairfax_location_to_oms_region_code_map.get(workspace_region, "USGV") - else: - logger.error("AKS Monitoring addon not supported in cloud : %s", cloud_name) - - default_workspace_resource_group = 'DefaultResourceGroup-' + workspace_region_code - default_workspace_name = 'DefaultWorkspace-{0}-{1}'.format(subscription_id, workspace_region_code) - default_workspace_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OperationalInsights' \ - '/workspaces/{2}'.format(subscription_id, default_workspace_resource_group, default_workspace_name) - resource_groups = cf_resource_groups(cmd.cli_ctx, subscription_id) - - # check if default RG exists - if resource_groups.check_existence(default_workspace_resource_group): - try: - resource = resources.get_by_id(default_workspace_resource_id, '2015-11-01-preview') - return resource.id - except HttpResponseError as ex: - if ex.status_code != 404: - raise ex - else: - ResourceGroup = cmd.get_models('ResourceGroup', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) - resource_group = ResourceGroup(location=workspace_region) - resource_groups.create_or_update(default_workspace_resource_group, resource_group) - - GenericResource = cmd.get_models('GenericResource', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) - generic_resource = GenericResource(location=workspace_region, properties={'sku': {'name': 'standalone'}}) - async_poller = resources.begin_create_or_update_by_id(default_workspace_resource_id, '2015-11-01-preview', - generic_resource) - - ws_resource_id = '' - while True: - result = async_poller.result(15) - if async_poller.done(): - ws_resource_id = result.id - break - - return ws_resource_id - - -def _ensure_container_insights_for_monitoring(cmd, workspace_resource_id): - # extract subscription ID and resource group from workspace_resource_id URL - parsed = parse_resource_id(workspace_resource_id) - subscription_id, resource_group = parsed["subscription"], parsed["resource_group"] - - from azure.core.exceptions import HttpResponseError - resources = cf_resources(cmd.cli_ctx, subscription_id) - try: - resource = resources.get_by_id(workspace_resource_id, '2015-11-01-preview') - location = resource.location - except HttpResponseError as ex: - raise ex - - unix_time_in_millis = int( - (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000.0) - - solution_deployment_name = 'ContainerInsights-{}'.format(unix_time_in_millis) - - # pylint: disable=line-too-long - template = { - "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", - "contentVersion": "1.0.0.0", - "parameters": { - "workspaceResourceId": { - "type": "string", - "metadata": { - "description": "Azure Monitor Log Analytics Resource ID" - } - }, - "workspaceRegion": { - "type": "string", - "metadata": { - "description": "Azure Monitor Log Analytics workspace region" - } - }, - "solutionDeploymentName": { - "type": "string", - "metadata": { - "description": "Name of the solution deployment" - } - } - }, - "resources": [ - { - "type": "Microsoft.Resources/deployments", - "name": "[parameters('solutionDeploymentName')]", - "apiVersion": "2017-05-10", - "subscriptionId": "[split(parameters('workspaceResourceId'),'/')[2]]", - "resourceGroup": "[split(parameters('workspaceResourceId'),'/')[4]]", - "properties": { - "mode": "Incremental", - "template": { - "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", - "contentVersion": "1.0.0.0", - "parameters": {}, - "variables": {}, - "resources": [ - { - "apiVersion": "2015-11-01-preview", - "type": "Microsoft.OperationsManagement/solutions", - "location": "[parameters('workspaceRegion')]", - "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')" - "[8], ')')]", - "properties": { - "workspaceResourceId": "[parameters('workspaceResourceId')]" - }, - "plan": { - "name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId')," - "'/')[8], ')')]", - "product": "[Concat('OMSGallery/', 'ContainerInsights')]", - "promotionCode": "", - "publisher": "Microsoft" - } - } - ] - }, - "parameters": {} - } - } - ] - } - - params = { - "workspaceResourceId": { - "value": workspace_resource_id - }, - "workspaceRegion": { - "value": location - }, - "solutionDeploymentName": { - "value": solution_deployment_name - } - } - - deployment_name = 'arc-k8s-monitoring-{}'.format(unix_time_in_millis) - # publish the Container Insights solution to the Log Analytics workspace - return _invoke_deployment(cmd, resource_group, deployment_name, template, params, - validate=False, no_wait=False, subscription_id=subscription_id) - - -def _get_container_insights_settings(cmd, cluster_resource_group_name, cluster_name, configuration_settings, - configuration_protected_settings, is_ci_extension_type): - - subscription_id = get_subscription_id(cmd.cli_ctx) - workspace_resource_id = '' - - if configuration_settings is not None: - if 'loganalyticsworkspaceresourceid' in configuration_settings: - configuration_settings['logAnalyticsWorkspaceResourceID'] = \ - configuration_settings.pop('loganalyticsworkspaceresourceid') - - if 'logAnalyticsWorkspaceResourceID' in configuration_settings: - workspace_resource_id = configuration_settings['logAnalyticsWorkspaceResourceID'] - - workspace_resource_id = workspace_resource_id.strip() - - if configuration_protected_settings is not None: - if 'proxyEndpoint' in configuration_protected_settings: - # current supported format for proxy endpoint is http(s)://:@: - # do some basic validation since the ci agent does the complete validation - proxy = configuration_protected_settings['proxyEndpoint'].strip().lower() - proxy_parts = proxy.split('://') - if (not proxy) or (not proxy.startswith('http://') and not proxy.startswith('https://')) or \ - (len(proxy_parts) != 2): - raise InvalidArgumentValueError( - 'proxyEndpoint url should in this format http(s)://:@:' - ) - logger.info("successfully validated proxyEndpoint url hence passing proxy endpoint to extension") - configuration_protected_settings['omsagent.proxy'] = configuration_protected_settings['proxyEndpoint'] - - if not workspace_resource_id: - workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring( - cmd, subscription_id, cluster_resource_group_name, cluster_name) - else: - if not is_valid_resource_id(workspace_resource_id): - raise InvalidArgumentValueError('{} is not a valid Azure resource ID.'.format(workspace_resource_id)) - - if is_ci_extension_type: - _ensure_container_insights_for_monitoring(cmd, workspace_resource_id).result() - - # extract subscription ID and resource group from workspace_resource_id URL - parsed = parse_resource_id(workspace_resource_id) - workspace_sub_id, workspace_rg_name, workspace_name = \ - parsed["subscription"], parsed["resource_group"], parsed["name"] - - log_analytics_client = cf_log_analytics(cmd.cli_ctx, workspace_sub_id) - log_analytics_workspace = log_analytics_client.workspaces.get(workspace_rg_name, workspace_name) - if not log_analytics_workspace: - raise InvalidArgumentValueError( - 'Fails to retrieve workspace by {}'.format(workspace_name)) - - shared_keys = log_analytics_client.shared_keys.get_shared_keys( - workspace_rg_name, workspace_name) - if not shared_keys: - raise InvalidArgumentValueError('Fails to retrieve shared key for workspace {}'.format( - log_analytics_workspace)) - configuration_protected_settings['omsagent.secret.wsid'] = log_analytics_workspace.customer_id - configuration_settings['logAnalyticsWorkspaceResourceID'] = workspace_resource_id - configuration_protected_settings['omsagent.secret.key'] = shared_keys.primary_shared_key - # set the domain for the ci agent for non azure public clouds - cloud_name = cmd.cli_ctx.cloud.name - if cloud_name.lower() == 'azurechinacloud': - configuration_settings['omsagent.domain'] = 'opinsights.azure.cn' - elif cloud_name.lower() == 'azureusgovernment': - configuration_settings['omsagent.domain'] = 'opinsights.azure.us' - elif cloud_name.lower() == 'usnat': - configuration_settings['omsagent.domain'] = 'opinsights.azure.eaglex.ic.gov' - elif cloud_name.lower() == 'ussec': - configuration_settings['omsagent.domain'] = 'opinsights.azure.microsoft.scloud' diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtension.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtension.py deleted file mode 100644 index a04893f55e7..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtension.py +++ /dev/null @@ -1,61 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument - -from ..vendored_sdks.v2021_05_01_preview.models import ( - Extension, - ScopeCluster, - ScopeNamespace, - Scope -) - -from .PartnerExtensionModel import PartnerExtensionModel - - -class DefaultExtension(PartnerExtensionModel): - def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, - scope, auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file): - - """Default validations & defaults for Create - Must create and return a valid 'Extension' object. - - """ - ext_scope = None - if scope is not None: - if scope.lower() == 'cluster': - scope_cluster = ScopeCluster(release_namespace=release_namespace) - ext_scope = Scope(cluster=scope_cluster, namespace=None) - elif scope.lower() == 'namespace': - scope_namespace = ScopeNamespace(target_namespace=target_namespace) - ext_scope = Scope(namespace=scope_namespace, cluster=None) - - create_identity = False - extension_instance = Extension( - extension_type=extension_type, - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version, - scope=ext_scope, - configuration_settings=configuration_settings, - configuration_protected_settings=configuration_protected_settings - ) - return extension_instance, name, create_identity - - def Update(self, extension, auto_upgrade_minor_version, release_train, version): - """Default validations & defaults for Update - Must create and return a valid 'Extension' object. - - """ - return Extension( - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version - ) - - def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): - pass diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtensionWithIdentity.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtensionWithIdentity.py deleted file mode 100644 index d1b134f6349..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/DefaultExtensionWithIdentity.py +++ /dev/null @@ -1,53 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument - -from ..vendored_sdks.v2021_05_01_preview.models import ( - Extension, - ScopeCluster, - ScopeNamespace, - Scope -) - -from .PartnerExtensionModel import PartnerExtensionModel - - -class DefaultExtensionWithIdentity(PartnerExtensionModel): - def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, - scope, auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file): - - """Default validations & defaults for Create - Must create and return a valid 'Extension' object. - - """ - ext_scope = None - if scope is not None: - if scope.lower() == 'cluster': - scope_cluster = ScopeCluster(release_namespace=release_namespace) - ext_scope = Scope(cluster=scope_cluster, namespace=None) - elif scope.lower() == 'namespace': - scope_namespace = ScopeNamespace(target_namespace=target_namespace) - ext_scope = Scope(namespace=scope_namespace, cluster=None) - - create_identity = True - extension_instance = Extension( - extension_type=extension_type, - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version, - scope=ext_scope, - configuration_settings=configuration_settings, - configuration_protected_settings=configuration_protected_settings, - ) - return extension_instance, name, create_identity - - def Update(self, extension, auto_upgrade_minor_version, release_train, version): - pass - - def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): - pass diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/OpenServiceMesh.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/OpenServiceMesh.py deleted file mode 100644 index 2622d65c276..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/OpenServiceMesh.py +++ /dev/null @@ -1,153 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument -# pylint: disable=redefined-outer-name -# pylint: disable=no-member - -from knack.log import get_logger - -from azure.cli.core.azclierror import InvalidArgumentValueError, RequiredArgumentMissingError - -from .PartnerExtensionModel import PartnerExtensionModel - -from ..vendored_sdks.v2021_05_01_preview .models import ( - Extension, - ScopeCluster, - Scope -) - -logger = get_logger(__name__) - - -class OpenServiceMesh(PartnerExtensionModel): - CHART_NAME = "osm-arc" - CHART_LOCATION = "https://azure.github.io/osm-azure" - - def Create(self, cmd, client, resource_group_name, cluster_name, name, cluster_type, extension_type, - scope, auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file): - - """ExtensionType 'microsoft.openservicemesh' specific validations & defaults for Create - Must create and return a valid 'Extension' object. - - """ - # NOTE-1: Replace default scope creation with your customization, if required - # Scope must always be cluster - ext_scope = None - if scope == 'namespace': - raise InvalidArgumentValueError("Invalid scope '{}'. This extension can be installed " - "only at 'cluster' scope.".format(scope)) - - scope_cluster = ScopeCluster(release_namespace=release_namespace) - ext_scope = Scope(cluster=scope_cluster, namespace=None) - - # version is a mandatory if release-train is staging or pilot - if version is None: - raise RequiredArgumentMissingError( - "A version must be provided for release-train {}.".format(release_train) - ) - # If the release-train is 'staging' or 'pilot' then auto-upgrade-minor-version MUST be set to False - if auto_upgrade_minor_version or auto_upgrade_minor_version is None: - auto_upgrade_minor_version = False - logger.warning("Setting auto-upgrade-minor-version to False since release-train is '%s'", release_train) - - # NOTE-2: Return a valid ExtensionInstance object, Instance name and flag for Identity - create_identity = False - - # _validate_tested_distro(cmd, resource_group_name, cluster_name, version) - - extension_instance = Extension( - extension_type=extension_type, - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version, - scope=ext_scope, - configuration_settings=configuration_settings, - configuration_protected_settings=configuration_protected_settings, - identity=None, - location="" - ) - return extension_instance, name, create_identity - - def Update(self, extension, auto_upgrade_minor_version, release_train, version): - """ExtensionType 'microsoft.openservicemesh' specific validations & defaults for Update - Must create and return a valid 'Extension' object. - - """ - # auto-upgrade-minor-version MUST be set to False if release_train is staging or pilot - if release_train.lower() in ['staging', 'pilot']: - if auto_upgrade_minor_version or auto_upgrade_minor_version is None: - auto_upgrade_minor_version = False - # Set version to None to always get the latest version - user cannot override - version = None - logger.warning("Setting auto-upgrade-minor-version to False since release-train is '%s'", release_train) - - return Extension( - auto_upgrade_minor_version=auto_upgrade_minor_version, - release_train=release_train, - version=version - ) - - def Delete(self, client, resource_group_name, cluster_name, name, cluster_type): - pass - - -# def _validate_tested_distro(cmd, cluster_resource_group_name, cluster_name, extension_version): - -# field_unavailable_error = '\"testedDistros\" field unavailable for version {0} of microsoft.openservicemesh, ' \ -# 'cannot determine if this Kubernetes distribution has been properly tested'.format(extension_version) - -# if version.parse(str(extension_version)) <= version.parse("0.8.3"): -# logger.warning(field_unavailable_error) -# return - -# subscription_id = get_subscription_id(cmd.cli_ctx) -# resources = cf_resources(cmd.cli_ctx, subscription_id) - -# cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Kubernetes' \ -# '/connectedClusters/{2}'.format(subscription_id, cluster_resource_group_name, cluster_name) - -# resource = resources.get_by_id(cluster_resource_id, '2020-01-01-preview') -# cluster_distro = resource.properties['distribution'].lower() - -# if cluster_distro == "general": -# logger.warning('Unable to determine if distro has been tested for microsoft.openservicemesh, ' -# 'kubernetes distro: \"general\"') -# return - -# tested_distros = _get_tested_distros(extension_version) - -# if tested_distros is None: -# logger.warning(field_unavailable_error) -# elif cluster_distro not in tested_distros.split(): -# logger.warning('Untested kubernetes distro for microsoft.openservicemesh, Kubernetes distro is %s', -# cluster_distro) - - -# def _get_tested_distros(chart_version): - -# try: -# chart_arc = ChartBuilder({ -# "name": OpenServiceMesh.CHART_NAME, -# "version": str(chart_version), -# "source": { -# "type": "repo", -# "location": OpenServiceMesh.CHART_LOCATION -# } -# }) -# except VersionError: -# raise InvalidArgumentValueError( -# "Invalid version '{}' for microsoft.openservicemesh".format(chart_version) -# ) - -# values = chart_arc.get_values() -# values_yaml = yaml.load(values.raw, Loader=yaml.FullLoader) - -# try: -# return values_yaml['OpenServiceMesh']['testedDistros'] -# except KeyError: -# return None diff --git a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/PartnerExtensionModel.py b/src/k8s-configuration/azext_k8s_configuration/partner_extensions/PartnerExtensionModel.py deleted file mode 100644 index 3c24c74c1ab..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/partner_extensions/PartnerExtensionModel.py +++ /dev/null @@ -1,26 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from abc import ABC, abstractmethod -from ..vendored_sdks.v2021_05_01_preview.models import Extension - - -class PartnerExtensionModel(ABC): - @abstractmethod - def Create(self, cmd, client, resource_group_name: str, cluster_name: str, name: str, cluster_type: str, - extension_type: str, scope: str, auto_upgrade_minor_version: bool, release_train: str, version: str, - target_namespace: str, release_namespace: str, configuration_settings: dict, - configuration_protected_settings: dict, configuration_settings_file: str, - configuration_protected_settings_file: str) -> Extension: - pass - - @abstractmethod - def Update(self, extension: Extension, auto_upgrade_minor_version: bool, - release_train: str, version: str) -> Extension: - pass - - @abstractmethod - def Delete(self, client, resource_group_name: str, cluster_name: str, name: str, cluster_type: str): - pass diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/ExtensionProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/ExtensionProvider.py deleted file mode 100644 index b3b7321a886..00000000000 --- a/src/k8s-configuration/azext_k8s_configuration/providers/ExtensionProvider.py +++ /dev/null @@ -1,192 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# pylint: disable=unused-argument,too-many-locals - -from knack.log import get_logger - -from azure.core.exceptions import HttpResponseError - -from azure.cli.core.azclierror import ResourceNotFoundError, MutuallyExclusiveArgumentError -from azure.cli.core.commands.client_factory import get_subscription_id -from azure.cli.core.util import sdk_no_wait - -from ..vendored_sdks.v2021_05_01_preview.models import Identity - -from ..partner_extensions.ContainerInsights import ContainerInsights -from ..partner_extensions.AzureDefender import AzureDefender -from ..partner_extensions.AzureMLKubernetes import AzureMLKubernetes -from ..partner_extensions.DefaultExtension import DefaultExtension -from ..partner_extensions.DefaultExtensionWithIdentity import DefaultExtensionWithIdentity - -from ..utils import get_cluster_rp, get_parent_api_version, read_config_settings_file, is_dogfood_cluster -from ..validators import ( - validate_scope_and_namespace, - validate_version_and_auto_upgrade, - validate_scope_after_customization -) - -from .._client_factory import cf_resources -from .._client_factory import k8s_configuration_extension_client - -from .. import consts - -logger = get_logger(__name__) - - -# A factory method to return the correct extension class based off of the extension name -def ExtensionFactory(extension_name): - extension_map = { - 'microsoft.azuremonitor.containers': ContainerInsights, - 'microsoft.azuredefender.kubernetes': AzureDefender, - 'microsoft.azureml.kubernetes': AzureMLKubernetes, - 'microsoft.flux': DefaultExtensionWithIdentity, - 'cassandradatacentersoperator': DefaultExtensionWithIdentity, - } - - # Return the extension if we find it in the map, else return the default - return extension_map.get(extension_name, DefaultExtension)() - - -class ExtensionProvider: - def __init__(self, cmd): - self.cmd = cmd - self.client = k8s_configuration_extension_client(cmd.cli_ctx) - - def show(self, resource_group_name, cluster_type, cluster_name, name): - # Determine ClusterRP - cluster_rp = get_cluster_rp(cluster_type) - try: - extension = self.client.get(resource_group_name, cluster_rp, - cluster_type, cluster_name, name) - return extension - except HttpResponseError as ex: - # Customize the error message for resources not found - if ex.response.status_code == 404: - # If Cluster not found - if ex.message.__contains__("(ResourceNotFound)"): - message = "{0} Verify that the cluster-type is correct and the resource exists.".format( - ex.message) - # If Configuration not found - elif ex.message.__contains__("Operation returned an invalid status code 'Not Found'"): - message = "(ExtensionNotFound) The Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration/" \ - "extensions/{3} could not be found!".format(cluster_rp, cluster_type, - cluster_name, name) - else: - message = ex.message - raise ResourceNotFoundError(message) from ex - raise ex - - def list(self, resource_group_name, cluster_type, cluster_name): - cluster_rp = get_cluster_rp(cluster_type) - return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - - def delete(self, resource_group_name, cluster_type, cluster_name, name, force, no_wait): - cluster_rp = get_cluster_rp(cluster_type) - - if not force: - logger.info("Delting the flux configuration from the cluster. This may take a minute...") - return sdk_no_wait(no_wait, self.client.begin_delete, resource_group_name, - cluster_rp, cluster_type, cluster_name, name, force_delete=force) - - def create(self, resource_group_name, cluster_type, cluster_name, name, - extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, - version=None, target_namespace=None, release_namespace=None, configuration_settings=None, - configuration_protected_settings=None, configuration_settings_file=None, - configuration_protected_settings_file=None, tags=None, no_wait=False): - """Create a new Extension Instance. - - """ - cluster_rp = get_cluster_rp(cluster_type) - extension_type_lower = extension_type.lower() - - # Configuration Settings & Configuration Protected Settings - if configuration_settings is not None and configuration_settings_file is not None: - raise MutuallyExclusiveArgumentError( - 'Error! Both configuration-settings and configuration-settings-file cannot be provided.' - ) - - if configuration_protected_settings is not None and configuration_protected_settings_file is not None: - raise MutuallyExclusiveArgumentError( - 'Error! Both configuration-protected-settings and configuration-protected-settings-file ' - 'cannot be provided.' - ) - - config_settings = {} - config_protected_settings = {} - # Get Configuration Settings from file - if configuration_settings_file is not None: - config_settings = read_config_settings_file(configuration_settings_file) - - if configuration_settings is not None: - for dicts in configuration_settings: - for key, value in dicts.items(): - config_settings[key] = value - - # Get Configuration Protected Settings from file - if configuration_protected_settings_file is not None: - config_protected_settings = read_config_settings_file(configuration_protected_settings_file) - - if configuration_protected_settings is not None: - for dicts in configuration_protected_settings: - for key, value in dicts.items(): - config_protected_settings[key] = value - - # Identity is not created by default. Extension type must specify if identity is required. - create_identity = False - extension_instance = None - - # Scope & Namespace validation - common to all extension-types - validate_scope_and_namespace(scope, release_namespace, target_namespace) - - # Give Partners a chance to their extensionType specific validations and to set value over-rides. - - # Get the extension class based on the extension name - extension_class = ExtensionFactory(extension_type_lower) - extension_instance, name, create_identity = extension_class.Create( - self.cmd, self.client, resource_group_name, cluster_name, name, cluster_type, extension_type_lower, scope, - auto_upgrade_minor_version, release_train, version, target_namespace, release_namespace, config_settings, - config_protected_settings, configuration_settings_file, configuration_protected_settings_file) - - # Common validations - validate_version_and_auto_upgrade(extension_instance.version, - extension_instance.auto_upgrade_minor_version) - validate_scope_after_customization(extension_instance.scope) - - # Create identity, if required - if create_identity and not is_dogfood_cluster(self.cmd): - extension_instance = self.__add_identity(extension_instance, - resource_group_name, - cluster_rp, - cluster_type, - cluster_name) - - logger.info("Starting extension creation on the cluster. This might take a minute...") - return sdk_no_wait(no_wait, self.client.begin_create, resource_group_name, cluster_rp, cluster_type, - cluster_name, name, extension_instance) - - def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name): - subscription_id = get_subscription_id(self.cmd.cli_ctx) - resources = cf_resources(self.cmd.cli_ctx, subscription_id) - - cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}'.format(subscription_id, - resource_group_name, - cluster_rp, - cluster_type, - cluster_name) - - if cluster_rp == consts.MANAGED_RP_NAMESPACE: - return extension_instance - parent_api_version = get_parent_api_version(cluster_rp) - try: - resource = resources.get_by_id(cluster_resource_id, parent_api_version) - location = str(resource.location.lower()) - except HttpResponseError as ex: - raise ex - identity_type = "SystemAssigned" - - extension_instance.identity = Identity(type=identity_type) - extension_instance.location = location - return extension_instance diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py index 229ad4fa7a8..a072f04f094 100644 --- a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py @@ -12,11 +12,25 @@ from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property from azure.cli.core.util import sdk_no_wait, user_confirmation +from azure.cli.core.commands.client_factory import get_subscription_id + from azure.core.exceptions import HttpResponseError from knack.log import get_logger -from .._client_factory import k8s_configuration_fluxconfig_client -from ..utils import get_cluster_rp, get_data_from_key_or_file, get_duration, has_prune_enabled, to_base64 +from .._client_factory import ( + cf_resources, + k8s_configuration_fluxconfig_client, + k8s_configuration_extension_client +) +from ..utils import ( + get_parent_api_version, + get_cluster_rp, + get_data_from_key_or_file, + get_duration, + has_prune_enabled, + to_base64, + is_dogfood_cluster +) from ..validators import ( validate_cc_registration, validate_known_hosts, @@ -34,7 +48,10 @@ RepositoryRefDefinition, KustomizationDefinition, ) -from .ExtensionProvider import ExtensionProvider +from ..vendored_sdks.v2021_05_01_preview.models import ( + Extension, + Identity +) from .SourceControlConfigurationProvider import SourceControlConfigurationProvider logger = get_logger(__name__) @@ -42,7 +59,7 @@ class FluxConfigurationProvider: def __init__(self, cmd): - self.extension_provider = ExtensionProvider(cmd) + self.extension_client = k8s_configuration_extension_client(cmd.cli_ctx) self.source_control_configuration_provider = SourceControlConfigurationProvider(cmd) self.cmd = cmd self.client = k8s_configuration_fluxconfig_client(cmd.cli_ctx) @@ -255,7 +272,7 @@ def _validate_source_control_config_not_installed(self, resource_group_name, clu consts.SCC_EXISTS_ON_CLUSTER_ERROR, consts.SCC_EXISTS_ON_CLUSTER_HELP) - def _validate_extension_install(self, resource_group_name, cluster_type, cluster_name, no_wait): + def _validate_extension_install(self, resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait): # Validate if the extension is installed, if not, install it extensions = self.extension_provider.list(resource_group_name, cluster_type, cluster_name) found_flux_extension = False @@ -266,11 +283,22 @@ def _validate_extension_install(self, resource_group_name, cluster_type, cluster if not found_flux_extension: logger.warning("'Microsoft.Flux' extension not found on the cluster, installing it now." " This may take a few minutes...") - self.extension_provider.create(resource_group_name, cluster_type, cluster_name, - "flux", consts.FLUX_EXTENSION_TYPE, - release_train=os.getenv(consts.FLUX_EXTENSION_RELEASETRAIN), - version=os.getenv(consts.FLUX_EXTENSION_VERSION), - no_wait=no_wait).result() + + # Create identity, if required + extension = Extension( + extension_type="microsoft.flux", + auto_upgrade_minor_version=True, + ) + if not is_dogfood_cluster(self.cmd): + extension = self.__add_identity(extension, + resource_group_name, + cluster_rp, + cluster_type, + cluster_name) + + logger.info("Starting extension creation on the cluster. This might take a minute...") + sdk_no_wait(no_wait, self.extension_client.begin_create, resource_group_name, cluster_rp, cluster_type, + cluster_name, "flux", extension).result() logger.warning("'Microsoft.Flux' extension was successfully installed on the cluster") def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, @@ -308,6 +336,30 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time local_auth_ref=local_auth_ref ) + def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name): + subscription_id = get_subscription_id(self.cmd.cli_ctx) + resources = cf_resources(self.cmd.cli_ctx, subscription_id) + + cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}'.format(subscription_id, + resource_group_name, + cluster_rp, + cluster_type, + cluster_name) + + if cluster_rp == consts.MANAGED_RP_NAMESPACE: + return extension_instance + parent_api_version = get_parent_api_version(cluster_rp) + try: + resource = resources.get_by_id(cluster_resource_id, parent_api_version) + location = str(resource.location.lower()) + except HttpResponseError as ex: + raise ex + identity_type = "SystemAssigned" + + extension_instance.identity = Identity(type=identity_type) + extension_instance.location = location + return extension_instance + def validate_and_get_repository_ref(branch, tag, semver, commit): validate_repository_ref(branch, tag, semver, commit) From 6d4d834941b17c6dccb57ebd0dfaa75d796a667e Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 7 Sep 2021 14:54:04 -0700 Subject: [PATCH 54/61] Fix style issues --- .../_client_factory.py | 5 ++- .../azext_k8s_configuration/custom.py | 34 ++----------------- .../providers/FluxConfigurationProvider.py | 28 +++++++-------- .../SourceControlConfigurationProvider.py | 2 +- src/k8s-configuration/setup.py | 2 +- 5 files changed, 23 insertions(+), 48 deletions(-) diff --git a/src/k8s-configuration/azext_k8s_configuration/_client_factory.py b/src/k8s-configuration/azext_k8s_configuration/_client_factory.py index bea14dcebfa..372adc3f1fd 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_client_factory.py +++ b/src/k8s-configuration/azext_k8s_configuration/_client_factory.py @@ -18,7 +18,10 @@ def k8s_configuration_fluxconfig_client(cli_ctx, *_): def k8s_configuration_sourcecontrol_client(cli_ctx, *_): - return k8s_configuration_client(cli_ctx, api_version=consts.SOURCE_CONTROL_API_VERSION).source_control_configurations + return k8s_configuration_client( + cli_ctx, + api_version=consts.SOURCE_CONTROL_API_VERSION + ).source_control_configurations def k8s_configuration_extension_client(cli_ctx, *_): diff --git a/src/k8s-configuration/azext_k8s_configuration/custom.py b/src/k8s-configuration/azext_k8s_configuration/custom.py index 181ce707b5f..61da5dcf0d2 100644 --- a/src/k8s-configuration/azext_k8s_configuration/custom.py +++ b/src/k8s-configuration/azext_k8s_configuration/custom.py @@ -5,7 +5,6 @@ # pylint: disable=unused-argument -from .providers.ExtensionProvider import ExtensionProvider from .providers.FluxConfigurationProvider import FluxConfigurationProvider from .providers.SourceControlConfigurationProvider import SourceControlConfigurationProvider from . import consts @@ -25,6 +24,7 @@ def sourcecontrol_create(cmd, client, resource_group_name, cluster_name, name, r operator_params, ssh_private_key, ssh_private_key_file, https_user, https_key, ssh_known_hosts, ssh_known_hosts_file, enable_helm_operator, helm_operator_params) + def sourcecontrol_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): provider = SourceControlConfigurationProvider(cmd) return provider.show(resource_group_name, cluster_type, cluster_name, name) @@ -89,35 +89,7 @@ def flux_config_create_kustomization(cmd, client, resource_group_name, cluster_t validation, force) -def flux_config_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False, yes=False): +def flux_config_delete(cmd, client, resource_group_name, cluster_type, + cluster_name, name, force=False, no_wait=False, yes=False): provider = FluxConfigurationProvider(cmd) return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait, yes) - - -# Extension Methods - -def extension_show(cmd, client, resource_group_name, cluster_type, cluster_name, name): - provider = ExtensionProvider(cmd) - return provider.show(resource_group_name, cluster_type, cluster_name, name) - - -def extension_list(cmd, client, resource_group_name, cluster_type, cluster_name): - provider = ExtensionProvider(cmd) - return provider.list(resource_group_name, cluster_type, cluster_name) - - -def extension_create(cmd, client, resource_group_name, cluster_type, cluster_name, name, - extension_type, scope=None, auto_upgrade_minor_version=None, release_train=None, - version=None, target_namespace=None, release_namespace=None, configuration_settings=None, - configuration_protected_settings=None, configuration_settings_file=None, - configuration_protected_settings_file=None, tags=None, no_wait=False): - provider = ExtensionProvider(cmd) - return provider.create(resource_group_name, cluster_type, cluster_name, name, extension_type, scope, - auto_upgrade_minor_version, release_train, version, target_namespace, - release_namespace, configuration_settings, configuration_protected_settings, - configuration_settings_file, configuration_protected_settings_file) - - -def extension_delete(cmd, client, resource_group_name, cluster_type, cluster_name, name, force=False, no_wait=False): - provider = ExtensionProvider(cmd) - return provider.delete(resource_group_name, cluster_type, cluster_name, name, force, no_wait) diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py index a072f04f094..dbe8547ac51 100644 --- a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py @@ -5,10 +5,6 @@ # pylint: disable=unused-argument -import os -from re import L -from ..confirm import user_confirmation_factory - from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property from azure.cli.core.util import sdk_no_wait, user_confirmation @@ -17,6 +13,7 @@ from azure.core.exceptions import HttpResponseError from knack.log import get_logger +from ..confirm import user_confirmation_factory from .._client_factory import ( cf_resources, k8s_configuration_fluxconfig_client, @@ -146,7 +143,7 @@ def create(self, resource_group_name, cluster_type, cluster_name, name, url=None ) self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name, no_wait) + self._validate_extension_install(resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait) logger.warning("Creating the flux configuration '%s' in the cluster. This may take a few minutes...", name) @@ -166,7 +163,7 @@ def create_source(self, resource_group_name, cluster_type, cluster_name, name, u # Validate the extension install if this is not a deferred command if not self._is_deferred(): self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name, no_wait) + self._validate_extension_install(resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait) if kind == consts.GIT: dp_source_kind = consts.GIT_REPOSITORY @@ -210,7 +207,7 @@ def create_kustomization(self, resource_group_name, cluster_type, cluster_name, # Validate the extension install if this is not a deferred command if not self._is_deferred(): self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name) - self._validate_extension_install(resource_group_name, cluster_type, cluster_name, no_wait=False) + self._validate_extension_install(resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait=False) flux_configuration = cached_get(self.cmd, self.client.get, resource_group_name=resource_group_name, flux_configuration_name=name, cluster_rp=cluster_rp, @@ -246,11 +243,14 @@ def delete(self, resource_group_name, cluster_type, cluster_name, name, force, n try: config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name) except HttpResponseError: - logger.warning("No flux configuration with name '%s' found on cluster '%s', so nothing to delete", name, cluster_name) + logger.warning("No flux configuration with name '%s' found on cluster '%s', so nothing to delete", + name, cluster_name) return None if has_prune_enabled(config): - logger.warning("Prune is enabled on one or more of your kustomizations. Deleting a Flux configuration with prune enabled will also delete the Kubernetes objects deployed by the kustomization(s).") + logger.warning("Prune is enabled on one or more of your kustomizations. Deleting a Flux " + "configuration with prune enabled will also delete the Kubernetes objects " + "deployed by the kustomization(s).") user_confirmation_factory(self.cmd, yes, "Do you want to continue?") if not force: @@ -274,7 +274,7 @@ def _validate_source_control_config_not_installed(self, resource_group_name, clu def _validate_extension_install(self, resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait): # Validate if the extension is installed, if not, install it - extensions = self.extension_provider.list(resource_group_name, cluster_type, cluster_name) + extensions = self.extension_client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) found_flux_extension = False for extension in extensions: if extension.extension_type.lower() == consts.FLUX_EXTENSION_TYPE: @@ -341,10 +341,10 @@ def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cl resources = cf_resources(self.cmd.cli_ctx, subscription_id) cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}'.format(subscription_id, - resource_group_name, - cluster_rp, - cluster_type, - cluster_name) + resource_group_name, + cluster_rp, + cluster_type, + cluster_name) if cluster_rp == consts.MANAGED_RP_NAMESPACE: return extension_instance diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/SourceControlConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/SourceControlConfigurationProvider.py index c2dbbe32fef..d5d497ac514 100644 --- a/src/k8s-configuration/azext_k8s_configuration/providers/SourceControlConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/SourceControlConfigurationProvider.py @@ -3,13 +3,13 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from ..validators import validate_cc_registration, validate_known_hosts, validate_url_with_params from azure.cli.core.azclierror import ResourceNotFoundError from azure.core.exceptions import HttpResponseError from knack.log import get_logger from .._client_factory import k8s_configuration_sourcecontrol_client from ..utils import fix_compliance_state, get_cluster_rp, get_data_from_key_or_file, to_base64 +from ..validators import validate_cc_registration, validate_known_hosts, validate_url_with_params from .. import consts from ..vendored_sdks.v2021_03_01.models import ( diff --git a/src/k8s-configuration/setup.py b/src/k8s-configuration/setup.py index 2cc6fc00e58..048614fdd87 100644 --- a/src/k8s-configuration/setup.py +++ b/src/k8s-configuration/setup.py @@ -51,4 +51,4 @@ packages=find_packages(), install_requires=DEPENDENCIES, package_data={'azext_k8s_configuration': ['azext_metadata.json']}, -) \ No newline at end of file +) From a655a01febbfda7eaabad053948a1bc6fa447a50 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Tue, 7 Sep 2021 15:30:36 -0700 Subject: [PATCH 55/61] Override extension variables --- src/k8s-configuration/azext_k8s_configuration/commands.py | 4 ++-- src/k8s-configuration/azext_k8s_configuration/custom.py | 2 +- .../providers/FluxConfigurationProvider.py | 7 +++++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/k8s-configuration/azext_k8s_configuration/commands.py b/src/k8s-configuration/azext_k8s_configuration/commands.py index 67c42428ed7..fee8ea6334b 100644 --- a/src/k8s-configuration/azext_k8s_configuration/commands.py +++ b/src/k8s-configuration/azext_k8s_configuration/commands.py @@ -28,7 +28,7 @@ def load_command_table(self, _): client_factory=k8s_configuration_sourcecontrol_client ) - with self.command_group('k8s-configuration flux', k8s_configuration_fluxconfig_sdk, client_factory=k8s_configuration_fluxconfig_sdk, is_experimental=True) as g: + with self.command_group('k8s-configuration flux', k8s_configuration_fluxconfig_sdk, client_factory=k8s_configuration_fluxconfig_client, is_experimental=True) as g: g.custom_command('create', 'flux_config_create', supports_no_wait=True) g.custom_command('list', "flux_config_list", table_transformer=fluxconfig_list_table_format) g.custom_show_command('show', 'flux_config_show', table_transformer=fluxconfig_show_table_format) @@ -36,7 +36,7 @@ def load_command_table(self, _): # g.custom_command('source create', 'flux_config_create_source', supports_local_cache=True) # g.custom_command('kustomization create', 'flux_config_create_kustomization', supports_local_cache=True) - with self.command_group('k8s-configuration', k8s_configuration_sourcecontrol_sdk, client_factory=k8s_configuration_sourcecontrol_sdk) as g: + with self.command_group('k8s-configuration', k8s_configuration_sourcecontrol_sdk, client_factory=k8s_configuration_sourcecontrol_client) as g: g.custom_command('create', 'sourcecontrol_create', deprecate_info=self.deprecate(redirect='k8s-configuration flux create')) g.custom_command('list', 'sourcecontrol_list', table_transformer=sourcecontrol_list_table_format, deprecate_info=self.deprecate(redirect='k8s-configuration flux list')) g.custom_show_command('show', 'sourcecontrol_show', table_transformer=sourcecontrol_show_table_format, deprecate_info=self.deprecate(redirect='k8s-configuration flux show')) diff --git a/src/k8s-configuration/azext_k8s_configuration/custom.py b/src/k8s-configuration/azext_k8s_configuration/custom.py index 61da5dcf0d2..57e5f61af4d 100644 --- a/src/k8s-configuration/azext_k8s_configuration/custom.py +++ b/src/k8s-configuration/azext_k8s_configuration/custom.py @@ -14,7 +14,7 @@ def sourcecontrol_create(cmd, client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, operator_instance_name=None, operator_namespace='default', - helm_operator_chart_version='1.2.0', operator_type='flux', operator_params='', + helm_operator_chart_version='1.4.0', operator_type='flux', operator_params='', ssh_private_key='', ssh_private_key_file='', https_user='', https_key='', ssh_known_hosts='', ssh_known_hosts_file='', enable_helm_operator=None, helm_operator_params=''): diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py index dbe8547ac51..5cb83844fd0 100644 --- a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py @@ -5,6 +5,8 @@ # pylint: disable=unused-argument +import os + from azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError from azure.cli.core.commands import cached_get, cached_put, upsert_to_collection, get_property from azure.cli.core.util import sdk_no_wait, user_confirmation @@ -284,10 +286,11 @@ def _validate_extension_install(self, resource_group_name, cluster_rp, cluster_t logger.warning("'Microsoft.Flux' extension not found on the cluster, installing it now." " This may take a few minutes...") - # Create identity, if required extension = Extension( extension_type="microsoft.flux", auto_upgrade_minor_version=True, + release_train = os.getenv(consts.FLUX_EXTENSION_RELEASETRAIN), + version=os.getenv(consts.FLUX_EXTENSION_VERSION) ) if not is_dogfood_cluster(self.cmd): extension = self.__add_identity(extension, @@ -358,7 +361,7 @@ def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cl extension_instance.identity = Identity(type=identity_type) extension_instance.location = location - return extension_instance + return extension_instance def validate_and_get_repository_ref(branch, tag, semver, commit): From 6e135f3405c8630458bff4282cddc67f8f870f11 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 8 Sep 2021 14:49:34 -0700 Subject: [PATCH 56/61] Strip newlines from known_hosts file --- .../providers/FluxConfigurationProvider.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py index 5fd7c536f87..7511ce1731d 100644 --- a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py @@ -315,6 +315,7 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file) if knownhost_data: validate_known_hosts(knownhost_data) + knownhost_data = knownhost_data.strip('\n') # Validate registration with the RP endpoint validate_cc_registration(self.cmd) From 579ec5c6b598396c5dcb866a50825ec7337034b7 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 8 Sep 2021 15:22:16 -0700 Subject: [PATCH 57/61] Update help text and validators --- src/k8s-configuration/README.rst | 60 ++++++++++++++++--- .../azext_k8s_configuration/_help.py | 2 +- .../azext_k8s_configuration/validators.py | 8 +-- 3 files changed, 56 insertions(+), 14 deletions(-) diff --git a/src/k8s-configuration/README.rst b/src/k8s-configuration/README.rst index a20cb951c98..78c42245fd3 100644 --- a/src/k8s-configuration/README.rst +++ b/src/k8s-configuration/README.rst @@ -11,11 +11,57 @@ az extension add --name k8s-configuration ``` ### Included Features -#### Kubernetes Configuration: -Kubernetes SourceControl Configuration: [more info](https://docs.microsoft.com/en-us/azure/kubernetessconfiguration/)\ + +#### Flux Configuration (Flux v2): +Flux Configuration (Flux v1) Configuration: [more info](https://docs.microsoft.com/en-us/azure/kubernetessconfiguration/)\ +*Examples:* + +##### Create a Flux Configuration (Flux v2) +``` +az k8s-configuration create flux \ + --resource-group groupName \ + --cluster-name clusterName \ + --cluster-type clusterType \ + --name configurationName \ + --namespace configurationNamespace \ + --scope cluster + --kind git \ + --url https://github.com/Azure/arc-k8s-demo \ + --branch main \ + --kustomization name=my-kustomization +``` + +##### Get a Flux Configuration (Flux v2) +``` +az k8s-configuration flux show \ + --resource-group groupName \ + --cluster-name clusterName \ + --cluster-type clusterType \ + --name configurationName +``` + +##### Delete a Flux Configuration (Flux v2) +``` +az k8s-configuration flux delete \ + --resource-group groupName \ + --cluster-name clusterName \ + --cluster-type clusterType \ + --name configurationName +``` + +##### List all Flux Configuration (Flux v2) on a cluster +``` +az k8s-configuration flux list \ + --resource-group groupName \ + --cluster-name clusterName \ + --cluster-type clusterType +``` + +#### Source Control Configuration (Flux v1): +Source Control Configuration (Flux v1) Configuration: [more info](https://docs.microsoft.com/en-us/azure/kubernetessconfiguration/)\ *Examples:* -##### Create a Source Control Configuration (Fluxv1) +##### Create a Source Control Configuration (Flux v1) ``` az k8s-configuration create \ --resource-group groupName \ @@ -31,7 +77,7 @@ az k8s-configuration create \ --helm-operator-params chartParameters ``` -##### Get a Source Control Configuration (Fluxv1) +##### Get a Source Control Configuration (Flux v1) ``` az k8s-configuration show \ --resource-group groupName \ @@ -40,7 +86,7 @@ az k8s-configuration show \ --name configurationName ``` -##### Delete a Source Control Configuration (Fluxv1) +##### Delete a Source Control Configuration (Flux v1) ``` az k8s-configuration delete \ --resource-group groupName \ @@ -49,7 +95,7 @@ az k8s-configuration delete \ --name configurationName ``` -##### Update a Source Control Configuration (Fluxv1) +##### Update a Source Control Configuration (Flux v1) ``` az k8s-configuration create \ --resource-group groupName \ @@ -63,7 +109,7 @@ az k8s-configuration create \ --helm-operator-params chartParameters ``` -##### List all Source Control Configuration (Fluxv1) on a cluster +##### List all Source Control Configuration (Flux v1) on a cluster ``` az k8s-configuration list \ --resource-group groupName \ diff --git a/src/k8s-configuration/azext_k8s_configuration/_help.py b/src/k8s-configuration/azext_k8s_configuration/_help.py index 22deffd9fb7..111c7e521cf 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_help.py +++ b/src/k8s-configuration/azext_k8s_configuration/_help.py @@ -69,7 +69,7 @@ text: |- az k8s-configuration flux create --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ - --kind git --url https://github.com/Azure/arc-k8s-demo --branch master --kustomization \\ + --kind git --url https://github.com/Azure/arc-k8s-demo --branch main --kustomization \\ name=my-kustomization """ diff --git a/src/k8s-configuration/azext_k8s_configuration/validators.py b/src/k8s-configuration/azext_k8s_configuration/validators.py index 43449950443..aa872d47316 100644 --- a/src/k8s-configuration/azext_k8s_configuration/validators.py +++ b/src/k8s-configuration/azext_k8s_configuration/validators.py @@ -27,17 +27,13 @@ def validate_namespace(namespace): if namespace.namespace: - __validate_k8s_name(namespace.namespace, "--namespace", 63) + __validate_k8s_name(namespace.namespace, "--namespace", 253) def validate_configuration_name(namespace): __validate_k8s_name(namespace.name, "--name", 63) -def validate_extension_name(namespace): - __validate_k8s_cr_name(namespace.name, "--name", 253) - - def validate_fluxconfig_name(namespace): __validate_k8s_cr_name(namespace.name, "--name", 63) @@ -57,7 +53,7 @@ def validate_kustomization(values): for item in values: key, value = item.split('=', 1) if key == "name": - __validate_k8s_name(value, key, 63) + __validate_k8s_cr_name(value, key, 63) elif key in consts.SYNC_INTERVAL_KEYS: validate_duration("sync-interval", value) elif key in consts.TIMEOUT_KEYS: From 75df9b1f0c05823bdf5d80a9da7056b536a21c60 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Wed, 8 Sep 2021 16:13:22 -0700 Subject: [PATCH 58/61] Strip newlines from known hosts --- .../providers/FluxConfigurationProvider.py | 3 +-- src/k8s-configuration/azext_k8s_configuration/utils.py | 8 +++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py index 7511ce1731d..752379c494c 100644 --- a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py @@ -312,10 +312,9 @@ def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, time validate_duration("--sync-interval", sync_interval) # Get the known hosts data and validate it - knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file) + knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file, strip_newline=True) if knownhost_data: validate_known_hosts(knownhost_data) - knownhost_data = knownhost_data.strip('\n') # Validate registration with the RP endpoint validate_cc_registration(self.cmd) diff --git a/src/k8s-configuration/azext_k8s_configuration/utils.py b/src/k8s-configuration/azext_k8s_configuration/utils.py index 2edc4d9ae7d..33a04fa170d 100644 --- a/src/k8s-configuration/azext_k8s_configuration/utils.py +++ b/src/k8s-configuration/azext_k8s_configuration/utils.py @@ -24,14 +24,14 @@ def get_cluster_rp(cluster_type): raise InvalidArgumentValueError("Error! Cluster type '{}' is not supported".format(cluster_type)) -def get_data_from_key_or_file(key, filepath): +def get_data_from_key_or_file(key, filepath, strip_newline=False): if key and filepath: raise MutuallyExclusiveArgumentError( consts.KEY_AND_FILE_TOGETHER_ERROR, consts.KEY_AND_FILE_TOGETHER_HELP) data = '' if filepath: - data = read_key_file(filepath) + data = read_key_file(filepath, strip_newline) elif key: data = key return data @@ -48,7 +48,7 @@ def read_config_settings_file(file_path): raise Exception("File {} is not a valid JSON file".format(file_path)) from ex -def read_key_file(path): +def read_key_file(path, strip_newline=False): try: with open(path, "r") as myfile: # user passed in filename data_list = myfile.readlines() # keeps newline characters intact @@ -56,6 +56,8 @@ def read_key_file(path): if (data_list_len) <= 0: raise Exception("File provided does not contain any data") raw_data = ''.join(data_list) + if strip_newline: + raw_data = raw_data.strip() return to_base64(raw_data) except Exception as ex: raise InvalidArgumentValueError( From c2605da96e08ce0d9d9e884d6d22aac595bf94d5 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 20 Sep 2021 11:41:24 -0700 Subject: [PATCH 59/61] Add provisioning state check for flux extension --- .../azext_k8s_configuration/_help.py | 18 +++++++++--------- .../azext_k8s_configuration/_params.py | 2 +- .../azext_k8s_configuration/consts.py | 4 ++++ .../providers/FluxConfigurationProvider.py | 11 ++++++++--- src/k8s-configuration/setup.py | 2 +- 5 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/k8s-configuration/azext_k8s_configuration/_help.py b/src/k8s-configuration/azext_k8s_configuration/_help.py index 111c7e521cf..8877c14fc21 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_help.py +++ b/src/k8s-configuration/azext_k8s_configuration/_help.py @@ -58,14 +58,14 @@ helps['k8s-configuration flux'] = """ type: group - short-summary: Commands to manage Flux V2 Kubernetes configurations. + short-summary: Commands to manage Flux v2 Kubernetes configurations. """ helps['k8s-configuration flux create'] = """ type: command - short-summary: Create a Kubernetes Flux Configuration. + short-summary: Create a Kubernetes Flux v2 Configuration. examples: - - name: Create a Kubernetes Flux Configuration + - name: Create a Kubernetes v2 Flux Configuration text: |- az k8s-configuration flux create --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myconfig --scope cluster --namespace my-namespace \\ @@ -75,9 +75,9 @@ helps['k8s-configuration flux list'] = """ type: command - short-summary: List Kubernetes Flux Configurations. + short-summary: List Kubernetes Flux v2 Configurations. examples: - - name: List all Kubernetes Flux Configurations on a cluster + - name: List all Kubernetes Flux v2 Configurations on a cluster text: |- az k8s-configuration flux list --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters @@ -85,9 +85,9 @@ helps['k8s-configuration flux show'] = """ type: command - short-summary: Show a Kubernetes Flux Configuration. + short-summary: Show a Kubernetes Flux v2 Configuration. examples: - - name: Show details of a Kubernetes Flux Configuration + - name: Show details of a Kubernetes Flux v2 Configuration text: |- az k8s-configuration flux show --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myconfig @@ -95,9 +95,9 @@ helps['k8s-configuration flux delete'] = """ type: command - short-summary: Delete a Kubernetes Flux Configuration. + short-summary: Delete a Kubernetes Flux v2 Configuration. examples: - - name: Delete an existing Kubernetes Flux Configuration + - name: Delete an existing Kubernetes Flux v2 Configuration text: |- az k8s-configuration flux delete --resource-group my-resource-group --cluster-name mycluster \\ --cluster-type connectedClusters --name myconfig diff --git a/src/k8s-configuration/azext_k8s_configuration/_params.py b/src/k8s-configuration/azext_k8s_configuration/_params.py index 233c7036a77..c8b4e3b164e 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_params.py +++ b/src/k8s-configuration/azext_k8s_configuration/_params.py @@ -109,7 +109,7 @@ def load_arguments(self, _): help='Specify whether to force delete the flux configuration from the cluster.') c.argument('yes', options_list=['--yes', '-y'], - help='Ignore confirmation prompts') + help='Do not prompt for confirmation') with self.argument_context('k8s-configuration') as c: c.argument('name', diff --git a/src/k8s-configuration/azext_k8s_configuration/consts.py b/src/k8s-configuration/azext_k8s_configuration/consts.py index 1b075da4808..b7cd7adbf10 100644 --- a/src/k8s-configuration/azext_k8s_configuration/consts.py +++ b/src/k8s-configuration/azext_k8s_configuration/consts.py @@ -82,6 +82,9 @@ SCC_EXISTS_ON_CLUSTER_ERROR = "Error! SourceControlConfigurations with flux already exist on the cluster" SCC_EXISTS_ON_CLUSTER_HELP = "Try removing all sourceControlConfigurations from the cluster before attempting to add fluxConfigurations" +FLUX_EXTENSION_NOT_SUCCEEDED_ERROR = "Error! 'Microsoft.Flux' extension is installed but not in a succeeded state on the cluster. Unable to proceed with fluxConfiguration install." +FLUX_EXTENSION_NOT_SUCCEEDED_HELP = "Try resolving the extension error on the cluster or removing and re-installing the extension." + HTTP_URL_NO_AUTH_WARNING = "Warning! https url is being used without https auth params, ensure the repository url provided is not a private repo" NO_KUSTOMIZATIONS_WARNING = "Warning! No kustomizations were specified for this configuration. The specified source may not be applied to the cluster." @@ -93,6 +96,7 @@ CC_REGISTRATION_ERROR = "Unable to fetch registration state of '{0}' provider. Failed to enable 'flux configuration' feature..." CC_PROVIDER_NAMESPACE = 'Microsoft.KubernetesConfiguration' REGISTERED = "Registered" +SUCCEEDED = "Succeeded" FLUX_EXTENSION_TYPE = "microsoft.flux" diff --git a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py index 752379c494c..7eb172720d0 100644 --- a/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py +++ b/src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py @@ -277,12 +277,12 @@ def _validate_source_control_config_not_installed(self, resource_group_name, clu def _validate_extension_install(self, resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait): # Validate if the extension is installed, if not, install it extensions = self.extension_client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) - found_flux_extension = False + flux_extension = None for extension in extensions: if extension.extension_type.lower() == consts.FLUX_EXTENSION_TYPE: - found_flux_extension = True + flux_extension = extension break - if not found_flux_extension: + if not flux_extension: logger.warning("'Microsoft.Flux' extension not found on the cluster, installing it now." " This may take a few minutes...") @@ -303,6 +303,11 @@ def _validate_extension_install(self, resource_group_name, cluster_rp, cluster_t sdk_no_wait(no_wait, self.extension_client.begin_create, resource_group_name, cluster_rp, cluster_type, cluster_name, "flux", extension).result() logger.warning("'Microsoft.Flux' extension was successfully installed on the cluster") + elif flux_extension.provisioning_state != consts.SUCCEEDED: + raise DeploymentError( + consts.FLUX_EXTENSION_NOT_SUCCEEDED_ERROR, + consts.FLUX_EXTENSION_NOT_SUCCEEDED_HELP + ) def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval, ssh_private_key, ssh_private_key_file, https_user, https_key, diff --git a/src/k8s-configuration/setup.py b/src/k8s-configuration/setup.py index 048614fdd87..16fe6039726 100644 --- a/src/k8s-configuration/setup.py +++ b/src/k8s-configuration/setup.py @@ -14,7 +14,7 @@ from distutils import log as logger logger.warn("Wheel is not available, disabling bdist_wheel hook") -VERSION = '1.2.0' +VERSION = '1.1.0-beta1' # The full list of classifiers is available at # https://pypi.python.org/pypi?%3Aaction=list_classifiers From de52744629426e3cf87e2cd84e88b9245a298997 Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 20 Sep 2021 15:24:34 -0700 Subject: [PATCH 60/61] Pin helm version --- k8s-custom-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s-custom-pipelines.yml b/k8s-custom-pipelines.yml index 75ad3a52f79..a90177d0248 100644 --- a/k8s-custom-pipelines.yml +++ b/k8s-custom-pipelines.yml @@ -30,7 +30,7 @@ stages: echo "Installing helm3" curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 chmod 700 get_helm.sh - ./get_helm.sh + ./get_helm.sh --version 3.6.3 echo "Installing kubectl" curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl" From e0744d0810395606a2229fa17c5450476378cc6a Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Mon, 11 Oct 2021 14:31:16 -0700 Subject: [PATCH 61/61] Remove validation from create command --- src/k8s-configuration/azext_k8s_configuration/_params.py | 2 +- src/k8s-configuration/azext_k8s_configuration/action.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/k8s-configuration/azext_k8s_configuration/_params.py b/src/k8s-configuration/azext_k8s_configuration/_params.py index c8b4e3b164e..adb18a9488e 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_params.py +++ b/src/k8s-configuration/azext_k8s_configuration/_params.py @@ -101,7 +101,7 @@ def load_arguments(self, _): help='Suspend the reconciliation of the source and kustomizations associated with this configuration') c.argument('kustomization', action=KustomizationAddAction, - help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'validation', 'force']", + help="Define kustomizations to sync sources with parameters ['name', 'path', 'depends_on', 'timeout', 'sync_interval', 'retry_interval', 'prune', 'force']", nargs='+') with self.argument_context('k8s-configuration flux delete') as c: diff --git a/src/k8s-configuration/azext_k8s_configuration/action.py b/src/k8s-configuration/azext_k8s_configuration/action.py index 9ba3aef1adc..020caa01eeb 100644 --- a/src/k8s-configuration/azext_k8s_configuration/action.py +++ b/src/k8s-configuration/azext_k8s_configuration/action.py @@ -31,7 +31,7 @@ def __call__(self, parser, namespace, values, option_string=None): retry_interval = value elif key in consts.TIMEOUT_KEYS: timeout = value - else: + elif key != 'validation': kwargs[key] = value except ValueError as ex: raise InvalidArgumentValueError('usage error: {} KEY=VALUE [KEY=VALUE ...]'