Skip to content

Commit

Permalink
fix for _ files
Browse files Browse the repository at this point in the history
  • Loading branch information
FumingZhang committed Dec 29, 2023
1 parent f9b715b commit 5271bb9
Show file tree
Hide file tree
Showing 12 changed files with 2,013 additions and 976 deletions.
17 changes: 7 additions & 10 deletions src/aks-preview/azext_aks_preview/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,20 @@ def __init__(self, cli_ctx=None):
register_aks_preview_resource_type()

acs_custom = CliCommandType(operations_tmpl='azext_aks_preview.custom#{}')
super(ContainerServiceCommandsLoader, self).__init__(cli_ctx=cli_ctx,
custom_command_type=acs_custom,
resource_type=CUSTOM_MGMT_AKS_PREVIEW)
super().__init__(
cli_ctx=cli_ctx,
custom_command_type=acs_custom,
resource_type=CUSTOM_MGMT_AKS_PREVIEW,
)

def load_command_table(self, args):
super(ContainerServiceCommandsLoader, self).load_command_table(args)
super().load_command_table(args)
from azext_aks_preview.commands import load_command_table
load_command_table(self, args)
return self.command_table

def load_arguments(self, command):
from sys import version_info
if version_info[0] < 3:
super(ContainerServiceCommandsLoader, self).load_arguments(command)
else:
super().load_arguments(command)

super().load_arguments(command)
from azext_aks_preview._params import load_arguments
load_arguments(self, command)

Expand Down
23 changes: 13 additions & 10 deletions src/aks-preview/azext_aks_preview/_client_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def get_auth_management_client(cli_ctx, scope=None, **_):
if matched:
subscription_id = matched.groupdict()['subscription']
else:
raise CLIError("{} does not contain subscription Id.".format(scope))
raise CLIError(f"{scope} does not contain subscription Id.")
return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION, subscription_id=subscription_id)


Expand Down Expand Up @@ -129,23 +129,22 @@ def get_resource_by_name(cli_ctx, resource_name, resource_type):
if not elements:
from azure.cli.core._profile import Profile
profile = Profile(cli_ctx=cli_ctx)
message = "The resource with name '{}' and type '{}' could not be found".format(
resource_name, resource_type)
message = f"The resource with name '{resource_name}' and type '{resource_type}' could not be found"
try:
subscription = profile.get_subscription(
cli_ctx.data['subscription_id'])
raise CLIError(
"{} in subscription '{} ({})'.".format(message, subscription['name'], subscription['id']))
except (KeyError, TypeError):
raise CLIError(
"{} in the current subscription.".format(message))
f"{message} in subscription '{subscription['name']} ({subscription['id']})'."
)
except (KeyError, TypeError) as exc:
raise CLIError(f"{message} in the current subscription.") from exc

elif len(elements) == 1:
return elements[0]
else:
raise CLIError(
"More than one resources with type '{}' are found with name '{}'.".format(
resource_type, resource_name))
f"More than one resources with type '{resource_type}' are found with name '{resource_name}'."
)


def get_msi_client(cli_ctx, subscription_id=None):
Expand All @@ -154,7 +153,11 @@ def get_msi_client(cli_ctx, subscription_id=None):


def get_providers_client_factory(cli_ctx, subscription_id=None):
return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, subscription_id=subscription_id).providers
return get_mgmt_service_client(
cli_ctx,
ResourceType.MGMT_RESOURCE_RESOURCES,
subscription_id=subscription_id
).providers


def get_keyvault_client(cli_ctx, subscription_id=None):
Expand Down
3 changes: 2 additions & 1 deletion src/aks-preview/azext_aks_preview/_completers.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,5 @@ def _get_location_from_resource_group(cli_ctx, resource_group_name):
# Print a warning if the user hit [TAB] but the `--resource-group` argument was incorrect.
# For example: "Warning: Resource group 'bogus' could not be found."
from argcomplete import warn
warn('Warning: {}'.format(err.message))
warn(f'Warning: {err.message}')
return None
97 changes: 57 additions & 40 deletions src/aks-preview/azext_aks_preview/_consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@
CONST_MANAGED_CLUSTER_SKU_TIER_STANDARD = "standard"
CONST_MANAGED_CLUSTER_SKU_TIER_PREMIUM = "premium"

CONST_OUTBOUND_MIGRATION_MULTIZONE_TO_NATGATEWAY_MSG = "Warning: this AKS cluster has multi-zonal nodepools, but NAT Gateway is not currently zone redundant. Migrating outbound connectivity to NAT Gateway could lead to a reduction in zone redundancy for this cluster. Continue?"
CONST_OUTBOUND_MIGRATION_MULTIZONE_TO_NATGATEWAY_MSG = (
"Warning: this AKS cluster has multi-zonal nodepools, but NAT Gateway is not currently zone redundant. "
"Migrating outbound connectivity to NAT Gateway could lead to a reduction in zone redundancy for this cluster. "
"Continue?"
)
# load balancer backend pool type
CONST_LOAD_BALANCER_BACKEND_POOL_TYPE_NODE_IP = "nodeIP"
CONST_LOAD_BALANCER_BACKEND_POOL_TYPE_NODE_IPCONFIGURATION = "nodeIPConfiguration"
Expand All @@ -77,8 +81,8 @@
CONST_PRIVATE_DNS_ZONE_NONE = "none"

# used to set identity profile (for kubelet)
CONST_MANAGED_IDENTITY_OPERATOR_ROLE = 'Managed Identity Operator'
CONST_MANAGED_IDENTITY_OPERATOR_ROLE_ID = 'f1a07417-d97a-45cb-824c-7a7467783830'
CONST_MANAGED_IDENTITY_OPERATOR_ROLE = "Managed Identity Operator"
CONST_MANAGED_IDENTITY_OPERATOR_ROLE_ID = "f1a07417-d97a-45cb-824c-7a7467783830"

# consts for upgrade channel
CONST_RAPID_UPGRADE_CHANNEL = "rapid"
Expand Down Expand Up @@ -168,31 +172,42 @@

# all supported addons
ADDONS = {
'http_application_routing': CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME,
'monitoring': CONST_MONITORING_ADDON_NAME,
'virtual-node': CONST_VIRTUAL_NODE_ADDON_NAME,
'kube-dashboard': CONST_KUBE_DASHBOARD_ADDON_NAME,
'azure-policy': CONST_AZURE_POLICY_ADDON_NAME,
'ingress-appgw': CONST_INGRESS_APPGW_ADDON_NAME,
"http_application_routing": CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME,
"monitoring": CONST_MONITORING_ADDON_NAME,
"virtual-node": CONST_VIRTUAL_NODE_ADDON_NAME,
"kube-dashboard": CONST_KUBE_DASHBOARD_ADDON_NAME,
"azure-policy": CONST_AZURE_POLICY_ADDON_NAME,
"ingress-appgw": CONST_INGRESS_APPGW_ADDON_NAME,
"confcom": CONST_CONFCOM_ADDON_NAME,
'open-service-mesh': CONST_OPEN_SERVICE_MESH_ADDON_NAME,
'azure-keyvault-secrets-provider': CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME,
'gitops': CONST_GITOPS_ADDON_NAME,
'web_application_routing': CONST_WEB_APPLICATION_ROUTING_KEY_NAME
"open-service-mesh": CONST_OPEN_SERVICE_MESH_ADDON_NAME,
"azure-keyvault-secrets-provider": CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME,
"gitops": CONST_GITOPS_ADDON_NAME,
"web_application_routing": CONST_WEB_APPLICATION_ROUTING_KEY_NAME,
}

ADDONS_DESCRIPTIONS = {
CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME: '- configure ingress with automatic public DNS name creation',
CONST_MONITORING_ADDON_NAME: '- turn on Log Analytics monitoring. Uses the Log Analytics Default Workspace if it exists, else creates one. Specify "--workspace-resource-id" to use an existing workspace.\nIf monitoring addon is enabled --no-wait argument will have no effect.',
CONST_VIRTUAL_NODE_ADDON_NAME: '- enable AKS Virtual Node. Requires --aci-subnet-name to provide the name of an existing subnet for the Virtual Node to use.\naci-subnet-name must be in the same vnet which is specified by --vnet-subnet-id (required as well).',
CONST_KUBE_DASHBOARD_ADDON_NAME: '- n/a',
CONST_AZURE_POLICY_ADDON_NAME: '- enable Azure policy. The Azure Policy add-on for AKS enables at-scale enforcements and safeguards on your clusters in a centralized, consistent manner.\nLearn more at aka.ms/aks/policy.',
CONST_INGRESS_APPGW_ADDON_NAME: '- enable Application Gateway Ingress Controller addon (PREVIEW).',
CONST_CONFCOM_ADDON_NAME: '- enable confcom addon, this will enable SGX device plugin by default (PREVIEW).',
CONST_OPEN_SERVICE_MESH_ADDON_NAME: '- enable Open Service Mesh addon (PREVIEW).',
CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME: '- enable Azure Keyvault Secrets Provider addon.',
CONST_GITOPS_ADDON_NAME: '- enable GitOps (PREVIEW).',
CONST_WEB_APPLICATION_ROUTING_KEY_NAME: '- enable web application routing (PREVIEW).'
CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME: "- configure ingress with automatic public DNS name creation",
CONST_MONITORING_ADDON_NAME: (
"- turn on Log Analytics monitoring. Uses the Log Analytics Default Workspace if it exists, "
'else creates one. Specify "--workspace-resource-id" to use an existing workspace.\n'
"If monitoring addon is enabled --no-wait argument will have no effect."
),
CONST_VIRTUAL_NODE_ADDON_NAME: (
"- enable AKS Virtual Node. Requires --aci-subnet-name to provide the name of an existing subnet for "
"the Virtual Node to use.\naci-subnet-name must be in the same vnet which is specified by "
"--vnet-subnet-id (required as well)."
),
CONST_KUBE_DASHBOARD_ADDON_NAME: "- n/a",
CONST_AZURE_POLICY_ADDON_NAME: (
"- enable Azure policy. The Azure Policy add-on for AKS enables at-scale enforcements and safeguards on "
"your clusters in a centralized, consistent manner.\nLearn more at aka.ms/aks/policy."
),
CONST_INGRESS_APPGW_ADDON_NAME: "- enable Application Gateway Ingress Controller addon (PREVIEW).",
CONST_CONFCOM_ADDON_NAME: "- enable confcom addon, this will enable SGX device plugin by default (PREVIEW).",
CONST_OPEN_SERVICE_MESH_ADDON_NAME: "- enable Open Service Mesh addon (PREVIEW).",
CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME: "- enable Azure Keyvault Secrets Provider addon.",
CONST_GITOPS_ADDON_NAME: "- enable GitOps (PREVIEW).",
CONST_WEB_APPLICATION_ROUTING_KEY_NAME: "- enable web application routing (PREVIEW).",
}

# consts for credential
Expand All @@ -218,22 +233,24 @@
# Moving away from 1:n release to avoid unwanted breaking changes with auto upgrades.
CONST_DRAFT_CLI_VERSION = "v0.0.22"

CONST_CUSTOM_CA_TEST_CERT = '-----BEGIN CERTIFICATE-----\n' \
'MIICljCCAX4CCQC9zUAgqqqrWzANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJQ\n' \
'TDAeFw0yMjA5MTQwNjIzMjdaFw0yMjA5MTUwNjIzMjdaMA0xC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IIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAopKNIIbvvcPCw9fc4KLX\n"
"KDtRZobp5L+/1hCN+3OGhk5NvSTpSUrFifxqc0o3IF7YkO3K1n2jAvCMXO16Bf9b\n"
"OAR7VkCrwGFVkXNjM4wvXAX8CNNvjqd1zDPXSKdE7Wd8k3fTzx6nGUM0UgljIPhH\n"
"yh4a4Zujd5Ig2P/ZSX0pGJm47JTtMu7MDFHVM5wRWcCrN/H0TCYPIvEOs0B8AZxc\n"
"p3TF7A6veT5U9pVhQ3Xl9JN6LvvLqPxG3ea10rdv9DYzaiXmSY3ujI3Ri1Q11uWC\n"
"dtrFIpFu5cHW2OBW+jBXxL0v8xQmkxTLik4BR/PLCl30wxKQNsq3pjDgu0mutKuu\n"
"5wIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAVEAIs/hLwTVCwpEXdoXR24LelNNuB\n"
"/8ptK6lyjE11XwfMN3yy7F2oB1lrA4rI3j9obpDsHDJBNB13bi/lKgvAcbIn/Tyu\n"
"RKThtUdPgxNnqDUyxnb3OofMF3gB8ePTu+jZpd3zrlEuxdl40ByATCSyOgR6DHMt\n"
"SDd+joypnOHFAeSM+V0AaTelXSCK9OAWSAp5e6S76a6lRx+D5Xl3hBedBI0tX59h\n"
"tEYNEGZaRElFU79WcEF0cH+ZW0+jJ95xE3thZffRz6QI6yF63m8aC9l9bbdJS2zg\n"
"Yv8W+lCZi//ODeOBUugr++z9uj+vGk47JDSpV0n4JOun3ALUDJ0gqmcS\n"
"-----END CERTIFICATE-----"
)

# consts for maintenance configuration schedule type
CONST_DAILY_MAINTENANCE_SCHEDULE = "Daily"
Expand Down
34 changes: 6 additions & 28 deletions src/aks-preview/azext_aks_preview/_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,28 +136,6 @@ def find_preview_versions(versions_bag):
return parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions(preview)))


def aks_versions_table_format(result):
"""Format get-versions results as a summary for display with "-o table"."""

# get preview orchestrator version
preview = {}

def find_preview_versions():
for orchestrator in result.get('orchestrators', []):
if orchestrator.get('isPreview', False):
preview[orchestrator['orchestratorVersion']] = True
find_preview_versions()

parsed = compile_jmes("""orchestrators[].{
kubernetesVersion: orchestratorVersion | set_preview(@),
upgrades: upgrades[].orchestratorVersion || [`None available`] | sort_versions(@) | set_preview_array(@) | join(`, `, @)
}""")
# use ordered dicts so headers are predictable
results = parsed.search(result, Options(
dict_cls=OrderedDict, custom_functions=_custom_functions(preview)))
return sorted(results, key=lambda x: version_to_tuple(x.get('kubernetesVersion')), reverse=True)


def version_to_tuple(version):
"""Removes preview suffix"""
if version.endswith('(preview)'):
Expand All @@ -181,7 +159,7 @@ def _custom_functions(preview_versions):
class CustomFunctions(functions.Functions): # pylint: disable=too-few-public-methods

@ functions.signature({'types': ['array']})
def _func_sort_versions(self, versions): # pylint: disable=no-self-use
def _func_sort_versions(self, versions):
"""Custom JMESPath `sort_versions` function that sorts an array of strings as software versions"""
try:
return sorted(versions, key=version_to_tuple)
Expand All @@ -196,26 +174,26 @@ def _func_set_preview_array(self, versions):
for i, _ in enumerate(versions):
versions[i] = self._func_set_preview(versions[i])
return versions
except(TypeError, ValueError):
except (TypeError, ValueError):
return versions

@ functions.signature({'types': ['string']})
def _func_set_preview(self, version): # pylint: disable=no-self-use
def _func_set_preview(self, version):
"""Custom JMESPath `set_preview` function that suffixes preview version"""
try:
if preview_versions.get(version, False):
return version + '(preview)'
return version
except(TypeError, ValueError):
except (TypeError, ValueError):
return version

@ functions.signature({'types': ['object']})
def _func_pprint_labels(self, labels): # pylint: disable=no-self-use
def _func_pprint_labels(self, labels):
"""Custom JMESPath `pprint_labels` function that pretty print labels"""
if not labels:
return ''
return ' '.join([
'{}={}'.format(k, labels[k])
f'{k}={labels[k]}'
for k in sorted(labels.keys())
])

Expand Down
7 changes: 4 additions & 3 deletions src/aks-preview/azext_aks_preview/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

# pylint: disable=too-many-lines
import os.path

from knack.help_files import helps
Expand All @@ -14,7 +15,7 @@
'$HOME', '.azure', 'aksServicePrincipal.json')

# AKS command help
helps['aks create'] = """
helps['aks create'] = f"""
type: command
short-summary: Create a new managed Kubernetes cluster.
parameters:
Expand All @@ -25,7 +26,7 @@
type: string
short-summary: Service principal used for authentication to Azure APIs.
long-summary: If not specified, a new service principal is created and cached at
{sp_cache} to be used by subsequent `az aks` commands.
{AKS_SERVICE_PRINCIPAL_CACHE} to be used by subsequent `az aks` commands.
- name: --skip-subnet-role-assignment
type: bool
short-summary: Skip role assignment for subnet (advanced networking).
Expand Down Expand Up @@ -656,7 +657,7 @@
- name: Create a kubernetes cluster with Azure Monitor Metrics enabled.
text: az aks create -g MyResourceGroup -n MyManagedCluster --enable-azuremonitormetrics
""".format(sp_cache=AKS_SERVICE_PRINCIPAL_CACHE)
"""

helps['aks scale'] = """
type: command
Expand Down
Loading

0 comments on commit 5271bb9

Please sign in to comment.