def update_containerapp_logic()

in src/azure-cli/azure/cli/command_modules/containerapp/custom.py [0:0]


def update_containerapp_logic(cmd,
                              name,
                              resource_group_name,
                              yaml=None,
                              image=None,
                              container_name=None,
                              min_replicas=None,
                              max_replicas=None,
                              scale_rule_name=None,
                              scale_rule_type="http",
                              scale_rule_http_concurrency=None,
                              scale_rule_metadata=None,
                              scale_rule_auth=None,
                              set_env_vars=None,
                              remove_env_vars=None,
                              replace_env_vars=None,
                              remove_all_env_vars=False,
                              cpu=None,
                              memory=None,
                              revision_suffix=None,
                              startup_command=None,
                              args=None,
                              tags=None,
                              no_wait=False,
                              from_revision=None,
                              ingress=None,
                              target_port=None,
                              workload_profile_name=None,
                              termination_grace_period=None,
                              registry_server=None,
                              registry_user=None,
                              registry_pass=None,
                              secret_volume_mount=None):
    _validate_subscription_registered(cmd, CONTAINER_APPS_RP)
    validate_revision_suffix(revision_suffix)

    # Validate that max_replicas is set to 0-1000
    if max_replicas is not None:
        if max_replicas < 1 or max_replicas > 1000:
            raise ArgumentUsageError('--max-replicas must be in the range [1,1000]')

    if yaml:
        if image or min_replicas or max_replicas or\
            set_env_vars or remove_env_vars or replace_env_vars or remove_all_env_vars or cpu or memory or\
                startup_command or args or tags:
            logger.warning('Additional flags were passed along with --yaml. These flags will be ignored, and the configuration defined in the yaml will be used instead')
        return update_containerapp_yaml(cmd=cmd, name=name, resource_group_name=resource_group_name, file_name=yaml, no_wait=no_wait, from_revision=from_revision)

    containerapp_def = None
    try:
        containerapp_def = ContainerAppClient.show(cmd=cmd, resource_group_name=resource_group_name, name=name)
    except:
        pass

    if not containerapp_def:
        raise ResourceNotFoundError("The containerapp '{}' does not exist".format(name))

    new_containerapp = {}
    new_containerapp["properties"] = {}
    if from_revision:
        try:
            r = ContainerAppClient.show_revision(cmd=cmd, resource_group_name=resource_group_name, container_app_name=name, name=from_revision)
        except CLIError as e:
            # Error handle the case where revision not found?
            handle_raw_exception(e)

        _update_revision_env_secretrefs(r["properties"]["template"]["containers"], name)
        new_containerapp["properties"]["template"] = r["properties"]["template"]

    # Doing this while API has bug. If env var is an empty string, API doesn't return "value" even though the "value" should be an empty string
    for container in safe_get(containerapp_def, "properties", "template", "containers", default=[]):
        if "env" in container:
            for e in container["env"]:
                if "value" not in e:
                    e["value"] = ""

    update_map = {}
    update_map['scale'] = min_replicas is not None or max_replicas is not None or scale_rule_name
    update_map['container'] = image or container_name or set_env_vars is not None or remove_env_vars is not None or replace_env_vars is not None or remove_all_env_vars or cpu or memory or startup_command is not None or args is not None or secret_volume_mount is not None
    update_map['ingress'] = ingress or target_port
    update_map['registry'] = registry_server or registry_user or registry_pass

    if tags:
        _add_or_update_tags(new_containerapp, tags)

    if revision_suffix is not None:
        new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
        new_containerapp["properties"]["template"]["revisionSuffix"] = revision_suffix

    if termination_grace_period is not None:
        safe_set(new_containerapp, "properties", "template", "terminationGracePeriodSeconds", value=termination_grace_period)

    if workload_profile_name:
        new_containerapp["properties"]["workloadProfileName"] = workload_profile_name

        parsed_managed_env = parse_resource_id(containerapp_def["properties"]["managedEnvironmentId"])
        managed_env_name = parsed_managed_env['name']
        managed_env_rg = parsed_managed_env['resource_group']
        managed_env_info = None
        try:
            managed_env_info = ManagedEnvironmentClient.show(cmd=cmd, resource_group_name=managed_env_rg, name=managed_env_name)
        except:
            pass

        if not managed_env_info:
            raise ValidationError("Error parsing the managed environment '{}' from the specified containerapp".format(managed_env_name))

        ensure_workload_profile_supported(cmd, managed_env_name, managed_env_rg, workload_profile_name, managed_env_info)

    # Containers
    if update_map["container"]:
        new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
        new_containerapp["properties"]["template"]["containers"] = containerapp_def["properties"]["template"]["containers"]
        if not container_name:
            if len(new_containerapp["properties"]["template"]["containers"]) == 1:
                container_name = new_containerapp["properties"]["template"]["containers"][0]["name"]
            else:
                raise ValidationError("Usage error: --container-name is required when adding or updating a container")

        # Check if updating existing container
        updating_existing_container = False
        for c in new_containerapp["properties"]["template"]["containers"]:
            if c["name"].lower() == container_name.lower():
                updating_existing_container = True

                if image is not None:
                    c["image"] = image

                if set_env_vars is not None:
                    if "env" not in c or not c["env"]:
                        c["env"] = []
                    # env vars
                    _add_or_update_env_vars(c["env"], parse_env_var_flags(set_env_vars))

                if replace_env_vars is not None:
                    # Remove other existing env_vars, then add them
                    c["env"] = []
                    _add_or_update_env_vars(c["env"], parse_env_var_flags(replace_env_vars))

                if remove_env_vars is not None:
                    if "env" not in c or not c["env"]:
                        c["env"] = []
                    # env vars
                    _remove_env_vars(c["env"], remove_env_vars)

                if remove_all_env_vars:
                    c["env"] = []

                if startup_command is not None:
                    if isinstance(startup_command, list) and not startup_command:
                        c["command"] = None
                    else:
                        c["command"] = startup_command
                if args is not None:
                    if isinstance(args, list) and not args:
                        c["args"] = None
                    else:
                        c["args"] = args
                if cpu is not None or memory is not None:
                    if "resources" in c and c["resources"]:
                        if cpu is not None:
                            c["resources"]["cpu"] = cpu
                        if memory is not None:
                            c["resources"]["memory"] = memory
                    else:
                        c["resources"] = {
                            "cpu": cpu,
                            "memory": memory
                        }
                if secret_volume_mount is not None:
                    new_containerapp["properties"]["template"]["volumes"] = containerapp_def["properties"]["template"]["volumes"]
                    if "volumeMounts" not in c or not c["volumeMounts"]:
                        # if no volume mount exists, create a new volume and then mount
                        volume_def = VolumeModel
                        volume_mount_def = VolumeMountModel
                        volume_def["name"] = _generate_secret_volume_name()
                        volume_def["storageType"] = "Secret"

                        volume_mount_def["volumeName"] = volume_def["name"]
                        volume_mount_def["mountPath"] = secret_volume_mount

                        if "volumes" not in new_containerapp["properties"]["template"] or new_containerapp["properties"]["template"]["volumes"] is None:
                            new_containerapp["properties"]["template"]["volumes"] = [volume_def]
                        else:
                            new_containerapp["properties"]["template"]["volumes"].append(volume_def)
                        c["volumeMounts"] = [volume_mount_def]
                    else:
                        if len(c["volumeMounts"]) > 1:
                            raise ValidationError("Usage error: --secret-volume-mount can only be used with a container that has a single volume mount, to define multiple volumes and mounts please use --yaml")
                        else:
                            # check that the only volume is of type secret
                            volume_name = c["volumeMounts"][0]["volumeName"]
                            for v in new_containerapp["properties"]["template"]["volumes"]:
                                if v["name"].lower() == volume_name.lower():
                                    if v["storageType"] != "Secret":
                                        raise ValidationError("Usage error: --secret-volume-mount can only be used to update volume mounts with volumes of type secret. To update other types of volumes please use --yaml")
                                    break
                            c["volumeMounts"][0]["mountPath"] = secret_volume_mount

        # If not updating existing container, add as new container
        if not updating_existing_container:
            if image is None:
                raise ValidationError("Usage error: --image is required when adding a new container")

            resources_def = None
            if cpu is not None or memory is not None:
                resources_def = ContainerResourcesModel
                resources_def["cpu"] = cpu
                resources_def["memory"] = memory

            container_def = ContainerModel
            container_def["name"] = container_name
            container_def["image"] = image
            container_def["env"] = []

            if set_env_vars is not None:
                # env vars
                _add_or_update_env_vars(container_def["env"], parse_env_var_flags(set_env_vars))

            if replace_env_vars is not None:
                # env vars
                _add_or_update_env_vars(container_def["env"], parse_env_var_flags(replace_env_vars))

            if remove_env_vars is not None:
                # env vars
                _remove_env_vars(container_def["env"], remove_env_vars)

            if remove_all_env_vars:
                container_def["env"] = []

            if startup_command is not None:
                if isinstance(startup_command, list) and not startup_command:
                    container_def["command"] = None
                else:
                    container_def["command"] = startup_command
            if args is not None:
                if isinstance(args, list) and not args:
                    container_def["args"] = None
                else:
                    container_def["args"] = args
            if resources_def is not None:
                container_def["resources"] = resources_def
            if secret_volume_mount is not None:
                new_containerapp["properties"]["template"]["volumes"] = containerapp_def["properties"]["template"]["volumes"]
                # generate a new volume name
                volume_def = VolumeModel
                volume_mount_def = VolumeMountModel
                volume_def["name"] = _generate_secret_volume_name()
                volume_def["storageType"] = "Secret"

                # mount the volume to the container
                volume_mount_def["volumeName"] = volume_def["name"]
                volume_mount_def["mountPath"] = secret_volume_mount
                container_def["volumeMounts"] = [volume_mount_def]
                if "volumes" not in new_containerapp["properties"]["template"]:
                    new_containerapp["properties"]["template"]["volumes"] = [volume_def]
                else:
                    new_containerapp["properties"]["template"]["volumes"].append(volume_def)

            new_containerapp["properties"]["template"]["containers"].append(container_def)
    # Scale
    if update_map["scale"]:
        new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
        if "scale" not in new_containerapp["properties"]["template"]:
            new_containerapp["properties"]["template"]["scale"] = {}
        if min_replicas is not None:
            new_containerapp["properties"]["template"]["scale"]["minReplicas"] = min_replicas
        if max_replicas is not None:
            new_containerapp["properties"]["template"]["scale"]["maxReplicas"] = max_replicas

    scale_def = None
    if min_replicas is not None or max_replicas is not None:
        scale_def = ScaleModel
        scale_def["minReplicas"] = min_replicas
        scale_def["maxReplicas"] = max_replicas
    # so we don't overwrite rules
    if safe_get(new_containerapp, "properties", "template", "scale", "rules"):
        new_containerapp["properties"]["template"]["scale"].pop("rules")
    if scale_rule_name:
        if not scale_rule_type:
            scale_rule_type = "http"
        scale_rule_type = scale_rule_type.lower()
        scale_rule_def = ScaleRuleModel
        curr_metadata = {}
        if scale_rule_http_concurrency:
            if scale_rule_type == 'http':
                curr_metadata["concurrentRequests"] = str(scale_rule_http_concurrency)
            elif scale_rule_type == 'tcp':
                curr_metadata["concurrentConnections"] = str(scale_rule_http_concurrency)
        metadata_def = parse_metadata_flags(scale_rule_metadata, curr_metadata)
        auth_def = parse_auth_flags(scale_rule_auth)
        if scale_rule_type == "http":
            scale_rule_def["name"] = scale_rule_name
            scale_rule_def["custom"] = None
            scale_rule_def["tcp"] = None
            scale_rule_def["http"] = {}
            scale_rule_def["http"]["metadata"] = metadata_def
            scale_rule_def["http"]["auth"] = auth_def
        elif scale_rule_type == "tcp":
            scale_rule_def["name"] = scale_rule_name
            scale_rule_def["custom"] = None
            scale_rule_def["http"] = None
            scale_rule_def["tcp"] = {}
            scale_rule_def["tcp"]["metadata"] = metadata_def
            scale_rule_def["tcp"]["auth"] = auth_def
        else:
            scale_rule_def["name"] = scale_rule_name
            scale_rule_def["http"] = None
            scale_rule_def["tcp"] = None
            scale_rule_def["custom"] = {}
            scale_rule_def["custom"]["type"] = scale_rule_type
            scale_rule_def["custom"]["metadata"] = metadata_def
            scale_rule_def["custom"]["auth"] = auth_def
        if not scale_def:
            scale_def = ScaleModel
        scale_def["rules"] = [scale_rule_def]
        new_containerapp["properties"]["template"]["scale"]["rules"] = scale_def["rules"]
    # Ingress
    if update_map["ingress"]:
        new_containerapp["properties"]["configuration"] = {} if "configuration" not in new_containerapp["properties"] else new_containerapp["properties"]["configuration"]
        if target_port is not None or ingress is not None:
            new_containerapp["properties"]["configuration"]["ingress"] = {}
            if ingress:
                new_containerapp["properties"]["configuration"]["ingress"]["external"] = ingress.lower() == "external"
            if target_port:
                new_containerapp["properties"]["configuration"]["ingress"]["targetPort"] = target_port

    # Registry
    if update_map["registry"]:
        new_containerapp["properties"]["configuration"] = {} if "configuration" not in new_containerapp["properties"] else new_containerapp["properties"]["configuration"]
        if "registries" in containerapp_def["properties"]["configuration"]:
            new_containerapp["properties"]["configuration"]["registries"] = containerapp_def["properties"]["configuration"]["registries"]
        if "registries" not in containerapp_def["properties"]["configuration"] or containerapp_def["properties"]["configuration"]["registries"] is None:
            new_containerapp["properties"]["configuration"]["registries"] = []

        registries_def = new_containerapp["properties"]["configuration"]["registries"]

        _get_existing_secrets(cmd, resource_group_name, name, containerapp_def)
        if "secrets" in containerapp_def["properties"]["configuration"] and containerapp_def["properties"]["configuration"]["secrets"]:
            new_containerapp["properties"]["configuration"]["secrets"] = containerapp_def["properties"]["configuration"]["secrets"]
        else:
            new_containerapp["properties"]["configuration"]["secrets"] = []

        if registry_server:
            if not registry_pass or not registry_user:
                if ACR_IMAGE_SUFFIX not in registry_server:
                    raise RequiredArgumentMissingError('Registry url is required if using Azure Container Registry, otherwise Registry username and password are required if using Dockerhub')
                logger.warning('No credential was provided to access Azure Container Registry. Trying to look up...')
                parsed = urlparse(registry_server)
                registry_name = (parsed.netloc if parsed.scheme else parsed.path).split('.')[0]
                registry_user, registry_pass, _ = _get_acr_cred(cmd.cli_ctx, registry_name)
            # Check if updating existing registry
            updating_existing_registry = False
            for r in registries_def:
                if r['server'].lower() == registry_server.lower():
                    updating_existing_registry = True
                    if registry_user:
                        r["username"] = registry_user
                    if registry_pass:
                        r["passwordSecretRef"] = store_as_secret_and_return_secret_ref(
                            new_containerapp["properties"]["configuration"]["secrets"],
                            r["username"],
                            r["server"],
                            registry_pass,
                            update_existing_secret=True,
                            disable_warnings=True)

            # If not updating existing registry, add as new registry
            if not updating_existing_registry:
                registry = RegistryCredentialsModel
                registry["server"] = registry_server
                registry["username"] = registry_user
                registry["passwordSecretRef"] = store_as_secret_and_return_secret_ref(
                    new_containerapp["properties"]["configuration"]["secrets"],
                    registry_user,
                    registry_server,
                    registry_pass,
                    update_existing_secret=True,
                    disable_warnings=True)

                registries_def.append(registry)

    if not revision_suffix:
        new_containerapp["properties"]["template"] = {} if "template" not in new_containerapp["properties"] else new_containerapp["properties"]["template"]
        new_containerapp["properties"]["template"]["revisionSuffix"] = None

    try:
        r = ContainerAppClient.update(
            cmd=cmd, resource_group_name=resource_group_name, name=name, container_app_envelope=new_containerapp, no_wait=no_wait)

        if not no_wait and "properties" in r and "provisioningState" in r["properties"] and r["properties"]["provisioningState"].lower() == "waiting":
            logger.warning('Containerapp update in progress. Please monitor the update using `az containerapp show -n {} -g {}`'.format(name, resource_group_name))

        return r
    except Exception as e:
        handle_raw_exception(e)