Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
cbd026a
Moved dapr arguments to env as a subgroup.
Mar 15, 2022
e37a07c
Added env variable options.
Mar 15, 2022
b582910
Changed revision mode set to revision set-mode.
Mar 15, 2022
7b33faa
Added env var options to revision copy.
Mar 15, 2022
35e6ca2
Fixed revision copy bug related to env secret refs.
Mar 15, 2022
43e98f5
Changed registry and secret delete to remove. Added registry param he…
Mar 15, 2022
4c47767
Merge branch 'containerapp' into bugfixes
runefa Mar 15, 2022
7c90ee0
Updating warning text.
Mar 16, 2022
8024682
Updated warning text once more.
Mar 16, 2022
3544c8c
Made name optional for revision copy if from-revision flag is passed.
Mar 16, 2022
0f7d7f2
Fixed whitespace style issues.
Mar 16, 2022
858f828
Styled clients and utils to pass pylint.
Mar 17, 2022
570b6cb
Finished client.py pylint fixes.
Mar 17, 2022
01f1bc3
Fixed pylint issues.
Mar 17, 2022
2893b55
Fixed flake8 commands and custom.
Mar 17, 2022
a63dbc6
Fixed flake issues in src.
Mar 17, 2022
5294ff9
Added license header to _sdk_models.
Mar 17, 2022
82f389c
Added confirmation for containerapp delete.
Mar 17, 2022
75327ff
Merged containerapp.
Mar 18, 2022
04b4705
Update helps for identity, revision. Removed env-var alias for set-en…
Mar 18, 2022
1003727
Removed app-subnet-resource-id.
Mar 18, 2022
ea6f741
Merge containerapp.
Mar 18, 2022
ab81c23
Updated infrastructure subnet param help.
Mar 18, 2022
8aa4e0a
Check if containerapp resource exists before attempting to delete.
Mar 18, 2022
e3b5ef6
Added check before deleting managed env.
Mar 18, 2022
d83e276
Changed error types to be more specific.
Mar 21, 2022
f9e3d96
Removed check before deletion. Removed comments.
Mar 21, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Finished client.py pylint fixes.
  • Loading branch information
Haroon Feisal committed Mar 17, 2022
commit 570b6cb9002077c3c5b2b86a6cc959f21dbe3ae4
59 changes: 29 additions & 30 deletions src/containerapp/azext_containerapp/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long, consider-using-f-string
# pylint: disable=line-too-long, consider-using-f-string, no-else-return, duplicate-string-formatting-argument

from distutils.filelist import findall
from operator import is_
from urllib.parse import urlparse
from azure.cli.command_modules.appservice.custom import (_get_acr_cred)
from azure.cli.core.azclierror import (ResourceNotFoundError, ValidationError, RequiredArgumentMissingError)
from azure.cli.core.azclierror import (ValidationError, RequiredArgumentMissingError)
from azure.cli.core.commands.client_factory import get_subscription_id
from knack.log import get_logger
from msrestazure.tools import parse_resource_id
from urllib.parse import urlparse

from ._clients import ContainerAppClient
from ._client_factory import handle_raw_exception, providers_client_factory, cf_resource_groups, log_analytics_client_factory, log_analytics_shared_key_client_factory
Expand Down Expand Up @@ -39,7 +37,7 @@ def _validate_subscription_registered(cmd, resource_provider, subscription_id=No
subscription_id, resource_provider, resource_provider))
except ValidationError as ex:
raise ex
except Exception:
except Exception: # pylint: disable=broad-except
pass


Expand All @@ -63,7 +61,7 @@ def _ensure_location_allowed(cmd, location, resource_provider, resource_type):
location, resource_provider, resource_type))
except ValidationError as ex:
raise ex
except Exception:
except Exception: # pylint: disable=broad-except
pass


Expand Down Expand Up @@ -119,7 +117,7 @@ def parse_secret_flags(secret_list):

def _update_revision_env_secretrefs(containers, name):
for container in containers:
if "env" in container:
if "env" in container:
for var in container["env"]:
if "secretRef" in var:
var["secretRef"] = var["secretRef"].replace("{}-".format(name), "")
Expand All @@ -140,11 +138,11 @@ def store_as_secret_and_return_secret_ref(secrets_list, registry_user, registry_
return registry_pass
else:
# If user passed in registry password
if (urlparse(registry_server).hostname is not None):
if urlparse(registry_server).hostname is not None:
registry_secret_name = "{server}-{user}".format(server=urlparse(registry_server).hostname.replace('.', ''), user=registry_user.lower())
else:
registry_secret_name = "{server}-{user}".format(server=registry_server.replace('.', ''), user=registry_user.lower())

for secret in secrets_list:
if secret['name'].lower() == registry_secret_name.lower():
if secret['value'].lower() != registry_pass.lower():
Expand All @@ -154,7 +152,7 @@ def store_as_secret_and_return_secret_ref(secrets_list, registry_user, registry_
raise ValidationError('Found secret with name \"{}\" but value does not equal the supplied registry password.'.format(registry_secret_name))
return registry_secret_name

logger.warning('Adding registry password as a secret with name \"{}\"'.format(registry_secret_name))
logger.warning('Adding registry password as a secret with name \"{}\"'.format(registry_secret_name)) # pylint: disable=logging-format-interpolation
secrets_list.append({
"name": registry_secret_name,
"value": registry_pass
Expand Down Expand Up @@ -185,18 +183,19 @@ def _get_default_log_analytics_location(cmd):
if res and getattr(res, 'resource_type', "") == "workspaces":
res_locations = getattr(res, 'locations', [])

if len(res_locations):
if len(res_locations) > 0:
location = res_locations[0].lower().replace(" ", "").replace("(", "").replace(")", "")
if location:
return location

except Exception:
except Exception: # pylint: disable=broad-except
return default_location
return default_location

# Generate random 4 character string
def _new_tiny_guid():
import random, string
import random
import string
return ''.join(random.choices(string.ascii_letters + string.digits, k=4))

# Follow same naming convention as Portal
Expand Down Expand Up @@ -230,15 +229,15 @@ def _generate_log_analytics_if_not_provided(cmd, logs_customer_id, logs_key, loc
log_analytics_location = location
try:
_ensure_location_allowed(cmd, log_analytics_location, "Microsoft.OperationalInsights", "workspaces")
except Exception:
except Exception: # pylint: disable=broad-except
log_analytics_location = _get_default_log_analytics_location(cmd)

from azure.cli.core.commands import LongRunningOperation
from azure.mgmt.loganalytics.models import Workspace

workspace_name = _generate_log_analytics_workspace_name(resource_group_name)
workspace_instance = Workspace(location=log_analytics_location)
logger.warning("Generating a Log Analytics workspace with name \"{}\"".format(workspace_name))
logger.warning("Generating a Log Analytics workspace with name \"{}\"".format(workspace_name)) # pylint: disable=logging-format-interpolation

poller = log_analytics_client.begin_create_or_update(resource_group_name, workspace_name, workspace_instance)
log_analytics_workspace = LongRunningOperation(cmd.cli_ctx)(poller)
Expand All @@ -249,7 +248,7 @@ def _generate_log_analytics_if_not_provided(cmd, logs_customer_id, logs_key, loc
resource_group_name=resource_group_name).primary_shared_key

except Exception as ex:
raise ValidationError("Unable to generate a Log Analytics workspace. You can use \"az monitor log-analytics workspace create\" to create one and supply --logs-customer-id and --logs-key")
raise ValidationError("Unable to generate a Log Analytics workspace. You can use \"az monitor log-analytics workspace create\" to create one and supply --logs-customer-id and --logs-key") from ex
elif logs_customer_id is None:
raise ValidationError("Usage error: Supply the --logs-customer-id associated with the --logs-key")
elif logs_key is None: # Try finding the logs-key
Expand Down Expand Up @@ -286,7 +285,7 @@ def _get_existing_secrets(cmd, resource_group_name, name, containerapp_def):
secrets = []
try:
secrets = ContainerAppClient.list_secrets(cmd=cmd, resource_group_name=resource_group_name, name=name)
except Exception as e:
except Exception as e: # pylint: disable=broad-except
handle_raw_exception(e)

containerapp_def["properties"]["configuration"]["secrets"] = secrets["value"]
Expand Down Expand Up @@ -318,7 +317,7 @@ def _add_or_update_secrets(containerapp_def, add_secrets):
containerapp_def["properties"]["configuration"]["secrets"].append(new_secret)

def _remove_registry_secret(containerapp_def, server, username):
if (urlparse(server).hostname is not None):
if urlparse(server).hostname is not None:
registry_secret_name = "{server}-{user}".format(server=urlparse(server).hostname.replace('.', ''), user=username.lower())
else:
registry_secret_name = "{server}-{user}".format(server=server.replace('.', ''), user=username.lower())
Expand All @@ -329,10 +328,10 @@ def _remove_secret(containerapp_def, secret_name):
if "secrets" not in containerapp_def["properties"]["configuration"]:
containerapp_def["properties"]["configuration"]["secrets"] = []

for i in range(0, len(containerapp_def["properties"]["configuration"]["secrets"])):
existing_secret = containerapp_def["properties"]["configuration"]["secrets"][i]
for index, value in enumerate(containerapp_def["properties"]["configuration"]["secrets"]):
existing_secret = value
if existing_secret["name"].lower() == secret_name.lower():
containerapp_def["properties"]["configuration"]["secrets"].pop(i)
containerapp_def["properties"]["configuration"]["secrets"].pop(index)
break

def _add_or_update_env_vars(existing_env_vars, new_env_vars, is_add=False):
Expand All @@ -344,7 +343,7 @@ def _add_or_update_env_vars(existing_env_vars, new_env_vars, is_add=False):
if existing_env_var["name"].lower() == new_env_var["name"].lower():
is_existing = True
if is_add:
logger.warning("Environment variable {} already exists. Replacing environment variable value.".format(new_env_var["name"]))
logger.warning("Environment variable {} already exists. Replacing environment variable value.".format(new_env_var["name"])) # pylint: disable=logging-format-interpolation

if "value" in new_env_var:
existing_env_var["value"] = new_env_var["value"]
Expand All @@ -360,24 +359,24 @@ def _add_or_update_env_vars(existing_env_vars, new_env_vars, is_add=False):
# If not updating existing env var, add it as a new env var
if not is_existing:
if not is_add:
logger.warning("Environment variable {} does not exist. Adding as new environment variable.".format(new_env_var["name"]))
logger.warning("Environment variable {} does not exist. Adding as new environment variable.".format(new_env_var["name"])) # pylint: disable=logging-format-interpolation
existing_env_vars.append(new_env_var)

def _remove_env_vars(existing_env_vars, remove_env_vars):
for old_env_var in remove_env_vars:

# Check if updating existing env var
is_existing = False
for i in range(0, len(existing_env_vars)):
existing_env_var = existing_env_vars[i]
for index, value in enumerate(existing_env_vars):
existing_env_var = value
if existing_env_var["name"].lower() == old_env_var.lower():
is_existing = True
existing_env_vars.pop(i)
existing_env_vars.pop(index)
break

# If not updating existing env var, add it as a new env var
if not is_existing:
logger.warning("Environment variable {} does not exist.".format(old_env_var))
logger.warning("Environment variable {} does not exist.".format(old_env_var)) # pylint: disable=logging-format-interpolation

def _add_or_update_tags(containerapp_def, tags):
if 'tags' not in containerapp_def:
Expand Down Expand Up @@ -478,7 +477,7 @@ def update_nested_dictionary(orig_dict, new_dict):
def _is_valid_weight(weight):
try:
n = int(weight)
if n >= 0 and n <= 100:
if 0 <= n <= 100:
return True
return False
except ValueError:
Expand Down Expand Up @@ -528,7 +527,7 @@ def _infer_acr_credentials(cmd, registry_server):
registry_user, registry_pass = _get_acr_cred(cmd.cli_ctx, registry_name)
return (registry_user, registry_pass)
except Exception as ex:
raise RequiredArgumentMissingError('Failed to retrieve credentials for container registry {}. Please provide the registry username and password'.format(registry_name))
raise RequiredArgumentMissingError('Failed to retrieve credentials for container registry {}. Please provide the registry username and password'.format(registry_name)) from ex


def _registry_exists(containerapp_def, registry_server):
Expand Down