From e298f5799535edd85c4182a28d88ae7938e40c0f Mon Sep 17 00:00:00 2001 From: Jonathan Innis Date: Thu, 22 Jul 2021 18:42:35 -0700 Subject: [PATCH] [k8s-configuration] Update sourceControlConfiguration SDK Models to Track2 (#3676) * Create pull.yml * Update pull.yml * Update azure-pipelines.yml * Initial commit of k8s-extension * Update CODEOWNERS * Update azure-pipelines.yml * Create pull.yml * Update pull.yml * Update pull.yml * Update pipelines file * Update k8s-configuration name * Update test script params * Update pipeline file * Remove codeowners * Update pipelines file * Update CODEOWNERS * Update private preview pipelines * Remove open service mesh from public release * Update pipeline files * Update custom pipelines files * Add publish step to k8s-configuration * Update pipeline to publish extension * Update public extension pipeline * Change condition variable * Update pipeline naming * Add version to public preview/private preview * Update pipelines * Add different testing based on private branch * Add annotations to extension model * Update k8s-custom-pipelines.yml * Update SDKs with Updated Swagger Spec for 2020-07-01-preview (#13) * Update sdks with updated swagger spec * Update version and history rst * Reorder release history timeline * Fix ExtensionInstanceForCreate for import * remove py2 bdist support * Add custom table formatting * Remove unnecessary files * Fix style issues * Fix branch based on comments * Update identity piece manually * Don't handle defaults at the CLI level * Remove defaults from CLI client * Check null target namespace with namespace scope * Update style * Add cassandra operator and location to model * Stage Public Version of k8s-extension 0.2.0 for official release (#15) * Create pull.yml * Update pull.yml * Update azure-pipelines.yml * Initial commit of k8s-extension * Update pipelines file * Update CODEOWNERS * Update private preview pipelines * Remove open service mesh from public release * Update pipeline files * Update public extension pipeline * Change condition variable * Add version to public preview/private preview * Update pipelines * Add different testing based on private branch * Add annotations to extension model * Update k8s-custom-pipelines.yml * Update SDKs with Updated Swagger Spec for 2020-07-01-preview (#13) * Update sdks with updated swagger spec * Update version and history rst * Reorder release history timeline * Fix ExtensionInstanceForCreate for import * remove py2 bdist support * Add custom table formatting * Remove unnecessary files * Fix style issues * Fix branch based on comments * Update identity piece manually * Don't handle defaults at the CLI level * Remove defaults from CLI client * Check null target namespace with namespace scope * Update style * Add cassandra operator and location to model Co-authored-by: action@github.com * Remove custom pipelines file * Update extension description, remove private const * Update pipeline file * Disable check ref docs * Disable refs docs * Update to include better create warning logs and remove update context (#20) * Update to include better create warning logs and remove update context * Remove help text for update * Fix spelling error * Update message * Fix k8s-extension conflict with private version * Fix style errors * Fix filename * add customization for microsoft.azureml.kubernetes (#23) * add customization for microsoft.azureml.kubernetes * Update release history Co-authored-by: Yue Yu Co-authored-by: jonathan-innis * Add E2E Testing from Separate branch into internal code (#26) * Add internal e2e testing * Change to testing folder * Inference CLI validation for Scoring FE (#24) * cli validation starter * added the call to the fe validation function * nodeport validation not required * test fix Co-authored-by: Jonathan Innis * legal warning added (#27) * Remove deprecated method logger.warn * Update k8s-custom-pipelines.yml for Azure Pipelines * Update k8s-custom-pipelines.yml for Azure Pipelines * Add Azure Defender to E2E testing (#28) * Add azure defender testing to e2e * Remove the debug flag * Add configuration testing * Fix pipeline failures * Make test script more intuitive * Remove parameter from testing * Add some debug * Fix wrong location for k8s config whl * Fix pip install upgrade issue * Fix pip install upgrade issue * Add Check for Provider Registration and Refactor (#19) * Add check for provider registration and refactor * Fix bug in checking registration * Add license header to utils * Update private key check and error messaging * Update based on refactoring * Fix failing tests * Add provider registration check * Create a test for uppercase url, address comments * Add blank line to fix style check * Testing increase to ubuntu-latest * Update k8s-configuration Models to Track2 (#63) * Update models to track2 * Increase k8s-configuration version number * Update kind version * Change error to warning because of DSA failure * Remove unneeded files Co-authored-by: action@github.com Co-authored-by: yuyue9284 <15863499+yuyue9284@users.noreply.github.com> Co-authored-by: Yue Yu Co-authored-by: Lia Kazakova <58274127+liakaz@users.noreply.github.com> --- src/k8s-configuration/HISTORY.rst | 8 + .../_client_factory.py | 9 +- .../azext_k8s_configuration/_consts.py | 7 + .../azext_k8s_configuration/_params.py | 8 +- .../azext_k8s_configuration/_utils.py | 61 ++ .../azext_k8s_configuration/_validators.py | 115 +++- .../azext_k8s_configuration/custom.py | 192 ++----- .../tests/latest/test_validators.py | 60 +- .../vendored_sdks/__init__.py | 18 +- .../vendored_sdks/_configuration.py | 82 ++- .../_source_control_configuration_client.py | 95 +++- .../vendored_sdks/{version.py => _version.py} | 10 +- .../vendored_sdks/aio/__init__.py | 10 + .../vendored_sdks/aio/_configuration.py | 67 +++ .../_source_control_configuration_client.py | 87 +++ .../vendored_sdks/aio/operations/__init__.py | 15 + .../aio/operations/_operations.py | 105 ++++ ...ource_control_configurations_operations.py | 420 ++++++++++++++ .../vendored_sdks/models/__init__.py | 62 +- .../vendored_sdks/models/_models.py | 482 ++++++++-------- .../vendored_sdks/models/_models_py3.py | 519 ++++++++--------- .../vendored_sdks/models/_paged_models.py | 40 -- ...urce_control_configuration_client_enums.py | 95 ++-- .../vendored_sdks/operations/__init__.py | 7 +- .../vendored_sdks/operations/_operations.py | 127 +++-- ...ource_control_configurations_operations.py | 529 ++++++++++-------- src/k8s-configuration/setup.py | 4 +- 27 files changed, 2033 insertions(+), 1201 deletions(-) create mode 100644 src/k8s-configuration/azext_k8s_configuration/_consts.py create mode 100644 src/k8s-configuration/azext_k8s_configuration/_utils.py rename src/k8s-configuration/azext_k8s_configuration/vendored_sdks/{version.py => _version.py} (84%) create mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/__init__.py create mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_configuration.py create mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_source_control_configuration_client.py create mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/__init__.py create mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_operations.py create mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_source_control_configurations_operations.py delete mode 100644 src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_paged_models.py diff --git a/src/k8s-configuration/HISTORY.rst b/src/k8s-configuration/HISTORY.rst index 7de17458634..b8ef4668e03 100644 --- a/src/k8s-configuration/HISTORY.rst +++ b/src/k8s-configuration/HISTORY.rst @@ -3,6 +3,14 @@ Release History =============== +1.1.0 +++++++++++++++++++ +* Update sourceControlConfiguration resource models to Track2 + +1.0.1 +++++++++++++++++++ +* Add provider registration check + 1.0.0 ++++++++++++++++++ * Support api-version 2021-03-01 diff --git a/src/k8s-configuration/azext_k8s_configuration/_client_factory.py b/src/k8s-configuration/azext_k8s_configuration/_client_factory.py index d294b6fdfa4..86cbd33b7f4 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_client_factory.py +++ b/src/k8s-configuration/azext_k8s_configuration/_client_factory.py @@ -3,13 +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_configuration(cli_ctx, *_): - from azure.cli.core.commands.client_factory import get_mgmt_service_client +def cf_k8s_configuration(cli_ctx, *_): from azext_k8s_configuration.vendored_sdks import SourceControlConfigurationClient return get_mgmt_service_client(cli_ctx, SourceControlConfigurationClient) def cf_k8s_configuration_operation(cli_ctx, _): return cf_k8s_configuration(cli_ctx).source_control_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-configuration/azext_k8s_configuration/_consts.py b/src/k8s-configuration/azext_k8s_configuration/_consts.py new file mode 100644 index 00000000000..e58470e7e78 --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/_consts.py @@ -0,0 +1,7 @@ +# -------------------------------------------------------------------------------------------- +# 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/_params.py b/src/k8s-configuration/azext_k8s_configuration/_params.py index 9198ef3882e..c9faab38cfb 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_params.py +++ b/src/k8s-configuration/azext_k8s_configuration/_params.py @@ -13,7 +13,7 @@ ) 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 ._validators import _validate_configuration_type, _validate_operator_namespace, _validate_operator_instance_name def load_arguments(self, _): @@ -38,7 +38,7 @@ def load_arguments(self, _): 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, + validator=_validate_configuration_type, arg_type=get_enum_type(['sourceControlConfiguration']), help='Type of the configuration') c.argument('enable_helm_operator', @@ -60,11 +60,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' ''') diff --git a/src/k8s-configuration/azext_k8s_configuration/_utils.py b/src/k8s-configuration/azext_k8s_configuration/_utils.py new file mode 100644 index 00000000000..6ad8e600636 --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/_utils.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. +# -------------------------------------------------------------------------------------------- + +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 index 0862de43205..47c6b97ca3a 100644 --- a/src/k8s-configuration/azext_k8s_configuration/_validators.py +++ b/src/k8s-configuration/azext_k8s_configuration/_validators.py @@ -4,34 +4,48 @@ # -------------------------------------------------------------------------------------------- import re -from azure.cli.core.azclierror import InvalidArgumentValueError +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): +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): +def _validate_operator_namespace(namespace): if namespace.operator_namespace: - __validate_k8s_name(namespace.operator_namespace, "--operator-namespace", 23) + _validate_k8s_name(namespace.operator_namespace, "--operator-namespace", 23) -def validate_operator_instance_name(namespace): +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.operator_instance_name, "--operator-instance-name", 23) # Create Parameter Validation -def validate_configuration_name(configuration_name): - __validate_k8s_name(configuration_name, "--name", 63) +def _validate_configuration_name(configuration_name): + _validate_k8s_name(configuration_name, "--name", 63) # Helper -def __validate_k8s_name(param_value, param_name, max_len): +def _validate_k8s_name(param_value, param_name, max_len): if len(param_value) > max_len: raise InvalidArgumentValueError( 'Error! Invalid {0}'.format(param_name), @@ -44,3 +58,86 @@ def __validate_k8s_name(param_value, param_name, max_len): 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-configuration/azext_k8s_configuration/custom.py b/src/k8s-configuration/azext_k8s_configuration/custom.py index de6f0dfc5ca..12a1bafe644 100644 --- a/src/k8s-configuration/azext_k8s_configuration/custom.py +++ b/src/k8s-configuration/azext_k8s_configuration/custom.py @@ -3,21 +3,17 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -import base64 -import io -from urllib.parse import urlparse -from azure.cli.core.azclierror import InvalidArgumentValueError, ResourceNotFoundError, \ - RequiredArgumentMissingError, MutuallyExclusiveArgumentError, CommandNotFoundError +from azure.cli.core.azclierror import ResourceNotFoundError, CommandNotFoundError, \ + RequiredArgumentMissingError +from azure.core.exceptions import HttpResponseError from knack.log import get_logger -from paramiko.ed25519key import Ed25519Key -from paramiko.hostkeys import HostKeyEntry -from paramiko.ssh_exception import SSHException -from Crypto.PublicKey import RSA, ECC, DSA +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 -from ._validators import validate_configuration_name logger = get_logger(__name__) @@ -27,12 +23,12 @@ def show_k8s_configuration(client, resource_group_name, cluster_name, name, clus """ # Determine ClusterRP - cluster_rp = __get_cluster_type(cluster_type) + 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: + return _fix_compliance_state(config) + except HttpResponseError as ex: # Customize the error message for resources not found if ex.response.status_code == 404: # If Cluster not found @@ -55,7 +51,7 @@ def show_k8s_configuration(client, resource_group_name, cluster_name, name, clus # pylint: disable=too-many-locals -def create_k8s_configuration(client, resource_group_name, cluster_name, name, repository_url, scope, cluster_type, +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='', @@ -65,10 +61,10 @@ def create_k8s_configuration(client, resource_group_name, cluster_name, name, re """ # Validate configuration name - validate_configuration_name(name) + _validate_configuration_name(name) # Determine ClusterRP - cluster_rp = __get_cluster_type(cluster_type) + cluster_rp = _get_cluster_type(cluster_type) # Determine operatorInstanceName if operator_instance_name is None: @@ -81,22 +77,25 @@ def create_k8s_configuration(client, resource_group_name, cluster_name, name, re helm_operator_properties.chart_version = helm_operator_chart_version.strip() helm_operator_properties.chart_values = helm_operator_params.strip() - protected_settings = validate_and_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) + 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_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_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, @@ -114,7 +113,7 @@ def create_k8s_configuration(client, resource_group_name, cluster_name, name, re config = client.create_or_update(resource_group_name, cluster_rp, cluster_type, cluster_name, name, source_control_configuration) - return __fix_compliance_state(config) + return _fix_compliance_state(config) def update_k8s_configuration(client, resource_group_name, cluster_name, name, cluster_type, @@ -188,7 +187,7 @@ def update_k8s_configuration(client, resource_group_name, cluster_name, name, cl def list_k8s_configuration(client, resource_group_name, cluster_name, cluster_type): - cluster_rp = __get_cluster_type(cluster_type) + cluster_rp = _get_cluster_type(cluster_type) return client.list(resource_group_name, cluster_rp, cluster_type, cluster_name) @@ -197,49 +196,27 @@ def delete_k8s_configuration(client, resource_group_name, cluster_name, name, cl """ # Determine ClusterRP - cluster_rp = __get_cluster_type(cluster_type) + 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) + return client.begin_delete(resource_group_name, cluster_rp, cluster_type, cluster_name, source_control_configuration_name) -def validate_and_get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key): +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) + 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 - invalid_rsa_key, invalid_ecc_key, invalid_dsa_key, invalid_ed25519_key = (False, False, False, False) if ssh_private_key_data != '': - try: - RSA.import_key(from_base64(ssh_private_key_data)) - except ValueError: - invalid_rsa_key = True - try: - ECC.import_key(from_base64(ssh_private_key_data)) - except ValueError: - invalid_ecc_key = True - try: - DSA.import_key(from_base64(ssh_private_key_data)) - except ValueError: - invalid_dsa_key = True - try: - key_obj = io.StringIO(from_base64(ssh_private_key_data).decode('utf-8')) - Ed25519Key(file_obj=key_obj) - except SSHException: - invalid_ed25519_key = True - - if invalid_rsa_key and invalid_ecc_key and invalid_dsa_key and invalid_ed25519_key: - 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') + _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) + 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', @@ -250,102 +227,3 @@ def validate_and_get_protected_settings(ssh_private_key, ssh_private_key_file, h 'Try providing both --https-user and --https-key together') return protected_settings - - -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 validate_url_with_params(repository_url, ssh_private_key_set, known_hosts_contents_set, https_auth_set): - scheme = urlparse(repository_url).scheme - - if scheme 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 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/tests/latest/test_validators.py b/src/k8s-configuration/azext_k8s_configuration/tests/latest/test_validators.py index ce3db8b84f4..a83a5ae2071 100644 --- a/src/k8s-configuration/azext_k8s_configuration/tests/latest/test_validators.py +++ b/src/k8s-configuration/azext_k8s_configuration/tests/latest/test_validators.py @@ -6,42 +6,40 @@ import unittest import base64 from azure.cli.core.azclierror import InvalidArgumentValueError, MutuallyExclusiveArgumentError -from azext_k8s_configuration.custom import validate_and_get_protected_settings, validate_url_with_params, validate_known_hosts +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 - +from Crypto.PublicKey import DSA 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" + err = "Error! --ssh-private-key provided in invalid format" with self.assertRaises(InvalidArgumentValueError) as cm: - validate_and_get_protected_settings(private_key_encoded, '', '', '') + _get_protected_settings(private_key_encoded, '', '', '') self.assertEqual(str(cm.exception), err) def test_rsa_private_key(self): rsa_key = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFZRUF1bVA5M09qRHdjdlEyZHZhRlJNNWYrMEhVSnFvOFJnbmdwaGN3NFZidnd1TVNoQTZFc2FyCjFsam1CNUNnT1NGNHJqNDIvcmdxMW1hWndoSUgvckdPSElNa0lIcjFrZmNKMnBrR3ZhK1NxVm4wWUhzMjBpUW02ay92ZXQKdXdVQ2J1QjlxSU5zL2h2b0ppQ21JMUVpVWZ4VGoxRFJCUG15OXR3Qm52bW5FS1kxZ2NhT2YrS2Y1aGhCc09pd00yZnBRTwp0aTlIcHVzM1JhNXpFeElWbjJzVitpRjVvV3ZZM1JQTTlKNXFPMXRObUtOWll6TjgzbDYxMlBzRmR1Vm1QM2NUUlJtK2pzCjdzZW5jY0U0RitzU0hQMlJpMk5DU0JvZ2RJOFR5VTlzeTM3Szl3bFJ5NGZkWWI1K1o3YUZjMjhTNDdDWlo5dTRFVXdWUEYKbjU4dTUzajU0empwdXNpei9ZWmx3MG5NeEQ5SXI0aHlJZ2s0NlUzVmdHR0NPUytZVTVZT2JURGhPRG5udk5VRkg2NVhCagpEM3l6WVJuRDA3b2swQ1JUR3RCOWMzTjBFNDBjUnlPeVpEQ0l5a0FPdHZXYnBUZzdnaXA2UDc4K2pLVlFnanFwRTVQdi9ICnl1dlB6cUJoUkpWcG5VR1dvWnFlcWJhd2N5RWZwdHFLaTNtWUdVMHBBQUFGa0U5cUs3SlBhaXV5QUFBQUIzTnphQzF5YzIKRUFBQUdCQUxwai9kem93OEhMME5uYjJoVVRPWC90QjFDYXFQRVlKNEtZWE1PRlc3OExqRW9RT2hMR3E5Wlk1Z2VRb0RraAplSzQrTnY2NEt0Wm1tY0lTQi82eGpoeURKQ0I2OVpIM0NkcVpCcjJ2a3FsWjlHQjdOdElrSnVwUDczcmJzRkFtN2dmYWlECmJQNGI2Q1lncGlOUklsSDhVNDlRMFFUNXN2YmNBWjc1cHhDbU5ZSEdqbi9pbitZWVFiRG9zRE5uNlVEcll2UjZick4wV3UKY3hNU0ZaOXJGZm9oZWFGcjJOMFR6UFNlYWp0YlRaaWpXV016Zk41ZXRkajdCWGJsWmo5M0UwVVp2bzdPN0hwM0hCT0JmcgpFaHo5a1l0alFrZ2FJSFNQRThsUGJNdCt5dmNKVWN1SDNXRytmbWUyaFhOdkV1T3dtV2ZidUJGTUZUeForZkx1ZDQrZU00CjZicklzLzJHWmNOSnpNUS9TSytJY2lJSk9PbE4xWUJoZ2prdm1GT1dEbTB3NFRnNTU3elZCUit1VndZdzk4czJFWnc5TzYKSk5Ba1V4clFmWE56ZEJPTkhFY2pzbVF3aU1wQURyYjFtNlU0TzRJcWVqKy9Qb3lsVUlJNnFST1Q3L3g4cnJ6ODZnWVVTVgphWjFCbHFHYW5xbTJzSE1oSDZiYWlvdDVtQmxOS1FBQUFBTUJBQUVBQUFHQkFMaElmSXFacUZKSFRXcllyN24rays4alR3ClFtcGJvWmc1YmZSWGdhdGljaEo4ZGlXOGlNblFFRVRBcFd0OU5FZ0tqbDRrSGRuSnoyUERkZzFIN0ExaHppbkNsdzZMTTAKYUkyMGxyR2NrWWpXNDRNd3ozYmRQNHlURTllSXRiM0pmN1pNSGpqek4rSy96bWN0eWdMeXFZSzVXYTljM1JnMXdIRWFNNAplakUvNDg4M25WUmJvSFJDcjFCVi8wQVVFTTZhNisrRHpVZW9WdWdWL3RsV3RVMlJuQlZ4eCtJS0FVSDZRTHJFU2JkUkRoCkVGUEFhRWtEb3crd3dDcFpqTXBhMHdRZXBDSkhwWkJLN1pBU25EU3R3Y2RKRE4yeHZzdVNOOGg0bkN0MlZWd0xRenJKeVAKU2VjcWM3M1hIc3E3VWx6ZU5veHlTVW9KZ2JjNTZoRzhWYS9ITlhsOUtkdkFlWUVzS1l1OW5NRUprVSt3VHo1KzUvM2wwVQpxSkErb0pTVTducjYydlVKQnljbXg0SFdBcjJ6QkR2QnFBUWMzRG9LWHczeVM1Z0c5Zkc0c25OUUkxOHVRSjdOSjdndHZHClpKRU56bTNJMmFTMzl5dndWZnFIMXpXVERxU2VNeWhYeWFnTkFEcGtCVEJIMVJQR2NtTFplclFmWWx1djVVUmFNTXdRQUEKQU1BdE9oNHFwUUhidm5tQ1RVakx4dXRrWnRaRlhNa0hmSTk5NS9Nd2RvWVY1eWRKV0pUVGsyKzB1QVBIcTZEejk2b3dWbQpjUkF2WDBDOVU5d3ZRMkpnR0Y1MDZzcmgzZkVpUzM2d1ArOFd0RjZ6ODd0enJwQnpQVHIxOGRONURCOEx5L3dXRk5BVTdqClBUbXM0dHlUY1VsRXR3eEt4TXJTNC9ROUZwMWozL3JNdnNZdGVaSVgycmN4YUhkWWJDVGJtTUpZS3lVTWVXTk56NXpub1EKcFcyd2NDSmpJc1MvS1F2WmR4cHZwNWd0RXE1WlEva3FvLzJVRWd1NHhwdDNWeUNma0FBQURCQVBOSHVEU1R0ZEpJWjdzcwpaQkVwcUE4TE54b1dMQ2RURnlpRERiUnpYOWVPTldkRFQ3NklaRE9HejczNXJhZUFSM2FiY0FhaUM0dDQwTFJTNGEyN29sCm9wK1dSak9wcjVNYUtOUnk4MCt6VWw3WUlSMjErKzVnMFVnNkRnQlBEdmFJSHFSTnRsZ2gyVXdTL0cva1lOaUlEY0JiS1EKOUcvdTI4ekRIRUtNL21YYS8wYnFtSm16ZUYvY1BLdHdScFE3clFoRnAwUkdFcnZtc0l4dDl6K0ZZZUdncjFBYUVTV0ZlTApmUmZsa0lnOVBWOEl0b09GN25qK2VtMkxkNTNCS1hSUUFBQU1FQXhDTFBueHFFVEsyMW5QOXFxQVYzMEZUUkhGNW9kRHg4ClpiYnZIbjgwdEgxQjYwZjRtTGJFRm56REZFR0NwS2Rwb3dyUXR6WUhnQzNBaGNJUE9BbXFXaDg0UEFPbisreHhFanNaQkwKRWhVWmNFUndkYTMzTnJDNTVEMzZxbDBMZEsrSGRuZUFzVGZhazh0bWVlOTJWb0RxdWovNGFSMjBmUTBJUFVzMU8rWHNRNQpGWVFYQzZndExHZGRzRVFoSDF6MTh6RGtWa1UwdEhlZkJaL2pFZXBiOEZScXoxR1hpT0hGK2xBZVE2b3crS0xlcWtCcXQ4CkZxMHhGdG90SlF4VnFWQUFBQUYycHZhVzV1YVhOQVJFVlRTMVJQVUMxUVRWVkdVRFpOQVFJRAotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K" - protected_settings = validate_and_get_protected_settings(rsa_key, '', '', '') + 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 = validate_and_get_protected_settings(private_key_encoded, '', '', '') + 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 = validate_and_get_protected_settings(ecdsa_key, '', '', '') + 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 = validate_and_get_protected_settings(ed25519_key, '', '', '') + protected_settings = _get_protected_settings(ed25519_key, '', '', '') self.assertEqual('sshPrivateKey' in protected_settings, True) self.assertEqual(protected_settings.get('sshPrivateKey'), ed25519_key) @@ -52,7 +50,7 @@ def test_long_operator_namespace(self): namespace = OperatorNamespace(operator_namespace) err = 'Error! Invalid --operator-namespace' with self.assertRaises(InvalidArgumentValueError) as cm: - validators.validate_operator_namespace(namespace) + validators._validate_operator_namespace(namespace) self.assertEqual(str(cm.exception), err) def test_long_operator_instance_name(self): @@ -60,7 +58,7 @@ def test_long_operator_instance_name(self): namespace = OperatorInstanceName(operator_instance_name) err = 'Error! Invalid --operator-instance-name' with self.assertRaises(InvalidArgumentValueError) as cm: - validators.validate_operator_instance_name(namespace) + validators._validate_operator_instance_name(namespace) self.assertEqual(str(cm.exception), err) def test_caps_operator_namespace(self): @@ -68,7 +66,7 @@ def test_caps_operator_namespace(self): namespace = OperatorNamespace(operator_namespace) err = 'Error! Invalid --operator-namespace' with self.assertRaises(InvalidArgumentValueError) as cm: - validators.validate_operator_namespace(namespace) + validators._validate_operator_namespace(namespace) self.assertEqual(str(cm.exception), err) def test_caps_operator_instance_name(self): @@ -76,68 +74,68 @@ def test_caps_operator_instance_name(self): namespace = OperatorInstanceName(operator_instance_name) err = 'Error! Invalid --operator-instance-name' with self.assertRaises(InvalidArgumentValueError) as cm: - validators.validate_operator_instance_name(namespace) + 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) + 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) + 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) + 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) + 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) + 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): - validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', True, False, False) + 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): - validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', False, True, False) + 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): - validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', False, False, True) + 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' + err = 'Error! An --ssh-private-key cannot be used with an http(s) url' with self.assertRaises(MutuallyExclusiveArgumentError) as cm: - validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', True, False, False) + 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' + err = 'Error! --ssh-known-hosts cannot be used with an http(s) url' with self.assertRaises(MutuallyExclusiveArgumentError) as cm: - validate_url_with_params('https://github.com/jonathan-innis/helm-operator-get-started-private.git', False, True, False) + 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: - validate_url_with_params('git@github.com:jonathan-innis/helm-operator-get-started-private.git', False, False, True) + 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) @@ -145,24 +143,24 @@ 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') - validate_known_hosts(known_hosts_encoded) + 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') - validate_known_hosts(known_hosts_encoded) + 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') - validate_known_hosts(known_hosts_encoded) + 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: - validate_known_hosts(known_hosts_encoded) + validators._validate_known_hosts(known_hosts_encoded) self.assertEqual(str(cm.exception), err) 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..f13062376d7 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,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. -# +# Licensed under the MIT License. See License.txt in the project root for 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 +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..645328abb1f 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_configuration.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_configuration.py @@ -1,49 +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. -# +# Licensed under the MIT License. See License.txt in the project root for 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 msrestazure import AzureConfiguration -from .version import VERSION +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. -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__(base_url) - - # Starting Autorest.Python 4.0.64, make connection pool activated by default - self.keep_alive = True + super(SourceControlConfigurationClientConfiguration, self).__init__(**kwargs) - 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.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-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..50b673797b5 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 @@ -1,16 +1,22 @@ # coding=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 msrest.service_client import SDKClient -from msrest import Serializer, Deserializer +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 @@ -18,38 +24,71 @@ from . import models -class SourceControlConfigurationClient(SDKClient): - """Use these APIs to create Source Control Configuration resources through ARM, for Kubernetes Clusters. +class SourceControlConfigurationClient(object): + """KubernetesConfiguration Client. - :ivar config: Configuration for client. - :vartype config: SourceControlConfigurationClientConfiguration - - :ivar source_control_configurations: SourceControlConfigurations operations - :vartype source_control_configurations: azure.mgmt.kubernetesconfiguration.operations.SourceControlConfigurationsOperations + :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.operations.Operations - - :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) + :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, credentials, subscription_id, base_url=None): - - self.config = SourceControlConfigurationClientConfiguration(credentials, subscription_id, base_url) - super(SourceControlConfigurationClient, self).__init__(self.config.credentials, self.config) + 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.api_version = '2021-03-01' 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._client, self._config, self._serialize, self._deserialize) self.operations = Operations( - self._client, self.config, self._serialize, self._deserialize) + 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-configuration/azext_k8s_configuration/vendored_sdks/version.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_version.py similarity index 84% rename from src/k8s-configuration/azext_k8s_configuration/vendored_sdks/version.py rename to src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_version.py index 9bd1dfac7ec..e5754a47ce6 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/version.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/_version.py @@ -1,13 +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. -# +# Licensed under the MIT License. See License.txt in the project root for 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. # -------------------------------------------------------------------------- -VERSION = "0.2.0" - +VERSION = "1.0.0b1" diff --git a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/__init__.py new file mode 100644 index 00000000000..ba52c91a7ba --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/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-configuration/azext_k8s_configuration/vendored_sdks/aio/_configuration.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_configuration.py new file mode 100644 index 00000000000..682d2762893 --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/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 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-configuration/azext_k8s_configuration/vendored_sdks/aio/_source_control_configuration_client.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/_source_control_configuration_client.py new file mode 100644 index 00000000000..2db9ca6cfeb --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/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-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/__init__.py new file mode 100644 index 00000000000..07db19b318c --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/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-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_operations.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/aio/operations/_operations.py new file mode 100644 index 00000000000..09d8376d112 --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/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.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-configuration/azext_k8s_configuration/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 new file mode 100644 index 00000000000..db8449803bd --- /dev/null +++ b/src/k8s-configuration/azext_k8s_configuration/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.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-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py index 86f85f9bcb5..95574a9920b 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/__init__.py @@ -1,73 +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. -# +# Licensed under the MIT License. See License.txt in the project root for 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. # -------------------------------------------------------------------------- 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 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 - 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 ._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, - OperatorType, OperatorScopeType, + OperatorType, ProvisioningStateType, - CreatedByType, ) __all__ = [ - 'AzureEntityResource', 'ComplianceStatus', 'ErrorDefinition', - 'ErrorResponse', 'ErrorResponseException', + 'ErrorResponse', 'HelmOperatorProperties', 'ProxyResource', 'Resource', 'ResourceProviderOperation', 'ResourceProviderOperationDisplay', + 'ResourceProviderOperationList', 'Result', 'SourceControlConfiguration', + 'SourceControlConfigurationList', 'SystemData', - 'TrackedResource', - 'SourceControlConfigurationPaged', - 'ResourceProviderOperationPaged', 'ComplianceStateType', + 'CreatedByType', + 'Enum0', + 'Enum1', 'MessageLevelType', - 'OperatorType', 'OperatorScopeType', + 'OperatorType', '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 index 676504953e7..00bd900ea10 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/models/_models.py @@ -1,123 +1,32 @@ # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# +# Licensed under the MIT License. See License.txt in the project root for 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 msrest.serialization import Model -from msrest.exceptions import HttpOperationError +from azure.core.exceptions import HttpResponseError +import msrest.serialization -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): +class ComplianceStatus(msrest.serialization.Model): """Compliance Status details. - Variables are only populated by the server, and will be ignored when - sending a request. + 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' + :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_03_01.models.ComplianceStateType :param last_config_applied: Datetime the configuration was last applied. - :type last_config_applied: datetime + :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' + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". :type message_level: str or - ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.MessageLevelType """ _validation = { @@ -131,7 +40,10 @@ class ComplianceStatus(Model): 'message_level': {'key': 'messageLevel', 'type': 'str'}, } - def __init__(self, **kwargs): + def __init__( + self, + **kwargs + ): super(ComplianceStatus, self).__init__(**kwargs) self.compliance_state = None self.last_config_applied = kwargs.get('last_config_applied', None) @@ -139,13 +51,13 @@ def __init__(self, **kwargs): self.message_level = kwargs.get('message_level', None) -class ErrorDefinition(Model): +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. + :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 @@ -161,41 +73,41 @@ class ErrorDefinition(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, **kwargs): + def __init__( + self, + **kwargs + ): super(ErrorDefinition, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) + self.code = kwargs['code'] + self.message = kwargs['message'] -class ErrorResponse(Model): +class ErrorResponse(msrest.serialization.Model): """Error response. - :param error: Error definition. - :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDefinition + 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): + 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. - """ + self.error = None - def __init__(self, deserialize, response, *args): - super(ErrorResponseException, self).__init__(deserialize, response, 'ErrorResponse', *args) - - -class HelmOperatorProperties(Model): +class HelmOperatorProperties(msrest.serialization.Model): """Properties for Helm operator. :param chart_version: Version of the operator Helm chart. @@ -209,28 +121,64 @@ class HelmOperatorProperties(Model): 'chart_values': {'key': 'chartValues', 'type': 'str'}, } - def __init__(self, **kwargs): + 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. +class Resource(msrest.serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. - 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. - 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} + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str - :ivar name: The name of the resource + :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" + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". :vartype type: str """ @@ -246,24 +194,24 @@ class ProxyResource(Resource): 'type': {'key': 'type', 'type': 'str'}, } - def __init__(self, **kwargs): + def __init__( + self, + **kwargs + ): super(ProxyResource, self).__init__(**kwargs) -class ResourceProviderOperation(Model): +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. + 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} + :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. + ~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 """ @@ -277,14 +225,17 @@ class ResourceProviderOperation(Model): 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, } - def __init__(self, **kwargs): + 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): +class ResourceProviderOperationDisplay(msrest.serialization.Model): """Display metadata associated with the operation. :param provider: Resource provider: Microsoft KubernetesConfiguration. @@ -304,7 +255,10 @@ class ResourceProviderOperationDisplay(Model): 'description': {'key': 'description', 'type': 'str'}, } - def __init__(self, **kwargs): + def __init__( + self, + **kwargs + ): super(ResourceProviderOperationDisplay, self).__init__(**kwargs) self.provider = kwargs.get('provider', None) self.resource = kwargs.get('resource', None) @@ -312,10 +266,40 @@ def __init__(self, **kwargs): self.description = kwargs.get('description', None) -class Result(Model): +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 + :param sample_property: Sample property of type string. :type sample_property: str """ @@ -323,7 +307,10 @@ class Result(Model): 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, } - def __init__(self, **kwargs): + def __init__( + self, + **kwargs + ): super(Result, self).__init__(**kwargs) self.sample_property = kwargs.get('sample_property', None) @@ -331,71 +318,63 @@ def __init__(self, **kwargs): 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. + 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} + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str - :ivar name: The name of the resource + :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" + :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. Default value: "default" . + :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. + :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. + :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 + :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" - . + :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). + ~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 + :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. + :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' + ~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.models.ProvisioningStateType - :ivar compliance_status: Compliance Status of the Configuration + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.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 + ~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}, @@ -405,6 +384,7 @@ class SourceControlConfiguration(ProxyResource): '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'}, @@ -418,11 +398,14 @@ class SourceControlConfiguration(ProxyResource): '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): + 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) @@ -436,30 +419,58 @@ def __init__(self, **kwargs): 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): +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' + :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 + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.CreatedByType :param created_at: The timestamp of resource creation (UTC). - :type created_at: datetime + :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' + :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 + ~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 = { @@ -471,7 +482,10 @@ class SystemData(Model): 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, } - def __init__(self, **kwargs): + 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) @@ -479,49 +493,3 @@ def __init__(self, **kwargs): 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 index b77227e4d97..259854d16de 100644 --- 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 @@ -1,123 +1,37 @@ # coding=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 msrest.serialization import Model -from msrest.exceptions import HttpOperationError +import datetime +from typing import Dict, List, Optional, Union +from azure.core.exceptions import HttpResponseError +import msrest.serialization -class Resource(Model): - """Resource. +from ._source_control_configuration_client_enums import * - 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): +class ComplianceStatus(msrest.serialization.Model): """Compliance Status details. - Variables are only populated by the server, and will be ignored when - sending a request. + 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' + :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_03_01.models.ComplianceStateType :param last_config_applied: Datetime the configuration was last applied. - :type last_config_applied: datetime + :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' + :param message_level: Level of the message. Possible values include: "Error", "Warning", + "Information". :type message_level: str or - ~azure.mgmt.kubernetesconfiguration.models.MessageLevelType + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.MessageLevelType """ _validation = { @@ -131,7 +45,14 @@ class ComplianceStatus(Model): 'message_level': {'key': 'messageLevel', 'type': 'str'}, } - def __init__(self, *, last_config_applied=None, message: str=None, message_level=None, **kwargs) -> None: + 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 @@ -139,13 +60,13 @@ def __init__(self, *, last_config_applied=None, message: str=None, message_level self.message_level = message_level -class ErrorDefinition(Model): +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. + :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 @@ -161,41 +82,44 @@ class ErrorDefinition(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, *, code: str, message: str, **kwargs) -> None: + def __init__( + self, + *, + code: str, + message: str, + **kwargs + ): super(ErrorDefinition, self).__init__(**kwargs) self.code = code self.message = message -class ErrorResponse(Model): +class ErrorResponse(msrest.serialization.Model): """Error response. - :param error: Error definition. - :type error: ~azure.mgmt.kubernetesconfiguration.models.ErrorDefinition + 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, *, error=None, **kwargs) -> None: + def __init__( + self, + **kwargs + ): 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): + self.error = None - super(ErrorResponseException, self).__init__(deserialize, response, 'ErrorResponse', *args) - -class HelmOperatorProperties(Model): +class HelmOperatorProperties(msrest.serialization.Model): """Properties for Helm operator. :param chart_version: Version of the operator Helm chart. @@ -209,28 +133,67 @@ class HelmOperatorProperties(Model): 'chart_values': {'key': 'chartValues', 'type': 'str'}, } - def __init__(self, *, chart_version: str=None, chart_values: str=None, **kwargs) -> None: + 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 ProxyResource(Resource): - """Proxy Resource. +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 + """ - The resource model definition for a Azure Resource Manager proxy resource. - It will not have tags and a location. + _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. + 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} + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str - :ivar name: The name of the resource + :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" + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". :vartype type: str """ @@ -246,24 +209,24 @@ class ProxyResource(Resource): 'type': {'key': 'type', 'type': 'str'}, } - def __init__(self, **kwargs) -> None: + def __init__( + self, + **kwargs + ): super(ProxyResource, self).__init__(**kwargs) -class ResourceProviderOperation(Model): +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. + 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} + :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. + ~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 """ @@ -277,14 +240,20 @@ class ResourceProviderOperation(Model): 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, } - def __init__(self, *, name: str=None, display=None, **kwargs) -> None: + 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(Model): +class ResourceProviderOperationDisplay(msrest.serialization.Model): """Display metadata associated with the operation. :param provider: Resource provider: Microsoft KubernetesConfiguration. @@ -304,7 +273,15 @@ class ResourceProviderOperationDisplay(Model): 'description': {'key': 'description', 'type': 'str'}, } - def __init__(self, *, provider: str=None, resource: str=None, operation: str=None, description: str=None, **kwargs) -> None: + 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 @@ -312,10 +289,42 @@ def __init__(self, *, provider: str=None, resource: str=None, operation: str=Non self.description = description -class Result(Model): +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 + :param sample_property: Sample property of type string. :type sample_property: str """ @@ -323,7 +332,12 @@ class Result(Model): 'sample_property': {'key': 'sampleProperty', 'type': 'str'}, } - def __init__(self, *, sample_property: str=None, **kwargs) -> None: + def __init__( + self, + *, + sample_property: Optional[str] = None, + **kwargs + ): super(Result, self).__init__(**kwargs) self.sample_property = sample_property @@ -331,71 +345,63 @@ def __init__(self, *, sample_property: str=None, **kwargs) -> 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. + 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} + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str - :ivar name: The name of the resource + :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" + :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. Default value: "default" . + :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. + :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. + :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 + :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" - . + :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). + ~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 + :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. + :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' + ~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.models.ProvisioningStateType - :ivar compliance_status: Compliance Status of the Configuration + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.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 + ~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}, @@ -405,6 +411,7 @@ class SourceControlConfiguration(ProxyResource): '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'}, @@ -418,11 +425,25 @@ class SourceControlConfiguration(ProxyResource): '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: + 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 @@ -436,30 +457,58 @@ def __init__(self, *, repository_url: str=None, operator_namespace: str="default self.helm_operator_properties = helm_operator_properties self.provisioning_state = None self.compliance_status = None - self.system_data = system_data -class SystemData(Model): +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' + :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 + ~azure.mgmt.kubernetesconfiguration.v2021_03_01.models.CreatedByType :param created_at: The timestamp of resource creation (UTC). - :type created_at: datetime + :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' + :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 + ~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 = { @@ -471,7 +520,17 @@ class SystemData(Model): '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: + 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 @@ -479,49 +538,3 @@ def __init__(self, *, created_by: str=None, created_by_type=None, created_at=Non 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 index 6708ac68cde..be122639f51 100644 --- 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 @@ -1,56 +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. -# +# Licensed under the MIT License. See License.txt in the project root for 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 enum import Enum +from enum import Enum, EnumMeta +from six import with_metaclass +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) -class ComplianceStateType(str, Enum): + 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) - pending = "Pending" - compliant = "Compliant" - noncompliant = "Noncompliant" - installed = "Installed" - failed = "Failed" +class ComplianceStateType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The compliance state of the configuration. + """ -class MessageLevelType(str, Enum): + PENDING = "Pending" + COMPLIANT = "Compliant" + NONCOMPLIANT = "Noncompliant" + INSTALLED = "Installed" + FAILED = "Failed" - error = "Error" - warning = "Warning" - information = "Information" +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 OperatorType(str, Enum): +class Enum0(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - flux = "Flux" + MICROSOFT_CONTAINER_SERVICE = "Microsoft.ContainerService" + MICROSOFT_KUBERNETES = "Microsoft.Kubernetes" +class Enum1(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): -class OperatorScopeType(str, Enum): + MANAGED_CLUSTERS = "managedClusters" + CONNECTED_CLUSTERS = "connectedClusters" - cluster = "cluster" - namespace = "namespace" +class MessageLevelType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Level of the message. + """ + ERROR = "Error" + WARNING = "Warning" + INFORMATION = "Information" -class ProvisioningStateType(str, Enum): +class OperatorScopeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Scope at which the operator will be installed. + """ - accepted = "Accepted" - deleting = "Deleting" - running = "Running" - succeeded = "Succeeded" - failed = "Failed" + CLUSTER = "cluster" + NAMESPACE = "namespace" +class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Type of the operator + """ -class CreatedByType(str, Enum): + FLUX = "Flux" - user = "User" - application = "Application" - managed_identity = "ManagedIdentity" - key = "Key" +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-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py index b6c0858d9a7..07db19b318c 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/__init__.py @@ -1,12 +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. -# +# Licensed under the MIT License. See License.txt in the project root for 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 ._source_control_configurations_operations import SourceControlConfigurationsOperations 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 index 5308b8f8270..4f46b393205 100644 --- a/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_operations.py +++ b/src/k8s-configuration/azext_k8s_configuration/vendored_sdks/operations/_operations.py @@ -1,101 +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. -# +# Licensed under the MIT License. See License.txt in the project root for 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 +import warnings -import uuid -from msrest.pipeline import ClientRawResponse +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 +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 directly this class, but create a Client instance that will create it for you and attach it as attribute. + 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. - :ivar api_version: The API version to be used with the HTTP request. Constant value: "2021-03-01". """ - models = models + 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 + 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` + 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'] - + url = self.list.metadata['url'] # type: ignore # Construct parameters - query_parameters = {} - query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') + 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 = {} - - # 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) + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) return request - def internal_paging(next_link=None): + 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) - response = self._client.send(request, stream=False, **operation_config) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response if response.status_code not in [200]: - raise models.ErrorResponseException(self._deserialize, response) - - return response + 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) - # Deserialize response - header_dict = None - if raw: - header_dict = {} - deserialized = models.ResourceProviderOperationPaged(internal_paging, self._deserialize.dependencies, header_dict) + return pipeline_response - return deserialized - list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.KubernetesConfiguration/operations'} # type: ignore 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 index 4b4a8599262..7808e3e5917 100644 --- 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 @@ -1,386 +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. -# +# Licensed under the MIT License. See License.txt in the project root for 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 +import warnings -import uuid -from msrest.pipeline import ClientRawResponse -from msrest.polling import LROPoller, NoPolling -from msrestazure.polling.arm_polling import ARMPolling +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 +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 directly this class, but create a Client instance that will create it for you and attach it as attribute. + 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. - :ivar api_version: The API version to be used with the HTTP request. Constant value: "2021-03-01". """ - models = models + 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 + 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): + 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). 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_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. + :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` + :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'] + url = self.get.metadata['url'] # type: ignore path_format_arguments = { - 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), + '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') + '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') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", 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 + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = self._client.get(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response if response.status_code not in [200]: - raise models.ErrorResponseException(self._deserialize, response) + 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 = None - if response.status_code == 200: - deserialized = self._deserialize('SourceControlConfiguration', response) + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_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}'} + 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, cluster_rp, cluster_resource_name, cluster_name, source_control_configuration_name, source_control_configuration, custom_headers=None, raw=False, **operation_config): + 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). 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_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. + :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` + :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'] + 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'), + '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') + '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') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", 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') + 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') - # Construct and send request - request = self._client.put(url, query_parameters, header_parameters, body_content) - response = self._client.send(request, stream=False, **operation_config) + 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]: - raise models.ErrorResponseException(self._deserialize, response) + 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 = None if response.status_code == 200: - deserialized = self._deserialize('SourceControlConfiguration', response) + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) + if response.status_code == 201: - deserialized = self._deserialize('SourceControlConfiguration', response) + deserialized = self._deserialize('SourceControlConfiguration', pipeline_response) - if raw: - client_raw_response = ClientRawResponse(deserialized, response) - return client_raw_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}'} - + 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, cluster_rp, cluster_resource_name, cluster_name, source_control_configuration_name, custom_headers=None, raw=False, **operation_config): + 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.metadata['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'), + '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') + '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') + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", 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 + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = self._client.delete(url, query_parameters, header_parameters) - response = self._client.send(request, stream=False, **operation_config) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response 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. + 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). 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_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. + :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` + :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: """ - 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 + 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, {}) - def get_long_running_output(response): - if raw: - client_raw_response = ClientRawResponse(None, response) - return client_raw_response + 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'), + } - 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) + 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 - 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}'} + 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, cluster_rp, cluster_resource_name, cluster_name, custom_headers=None, raw=False, **operation_config): + 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). 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_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 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` + :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'] + url = self.list.metadata['url'] # type: ignore path_format_arguments = { - 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), + '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') + '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') + 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 = {} - - # 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) + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) return request - def internal_paging(next_link=None): + 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) - response = self._client.send(request, stream=False, **operation_config) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response if response.status_code not in [200]: - raise models.ErrorResponseException(self._deserialize, response) - - return response + 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) - # Deserialize response - header_dict = None - if raw: - header_dict = {} - deserialized = models.SourceControlConfigurationPaged(internal_paging, self._deserialize.dependencies, header_dict) + return pipeline_response - return deserialized - list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'} + 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-configuration/setup.py b/src/k8s-configuration/setup.py index d6aa1b2377d..9579d8ebbe3 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.0' +VERSION = '1.1.0' # The full list of classifiers is available at # https://pypi.python.org/pypi?%3Aaction=list_classifiers