"""
Autogenerated state module using `pop-create-idem <https://gitlab.com/saltstack/pop/pop-create-idem>`__

hub.exec.boto3.client.emr.describe_job_flows
hub.exec.boto3.client.emr.run_job_flow
hub.exec.boto3.client.emr.terminate_job_flows
"""



from typing import *
import dict_tools.differ as differ
async def present(hub, ctx, name: Text, instances: Dict, log_uri: Text = None, log_encryption_kms_key_id: Text = None, additional_info: Text = None, ami_version: Text = None, release_label: Text = None, steps: List = None, bootstrap_actions: List = None, supported_products: List = None, new_supported_products: List = None, applications: List = None, configurations: List = None, visible_to_all_users: bool = None, job_flow_role: Text = None, service_role: Text = None, tags: List = None, security_configuration: Text = None, auto_scaling_role: Text = None, scale_down_behavior: Text = None, custom_ami_id: Text = None, ebs_root_volume_size: int = None, repo_upgrade_on_boot: Text = None, kerberos_attributes: Dict = None, step_concurrency_level: int = None, managed_scaling_policy: Dict = None, placement_group_configs: List = None)  -> Dict[str, Any]:
    r'''
    **Autogenerated function**
    
    RunJobFlow creates and starts running a new cluster (job flow). The cluster runs the steps specified. After the
    steps complete, the cluster stops and the HDFS partition is lost. To prevent loss of data, configure the last
    step of the job flow to store results in Amazon S3. If the JobFlowInstancesConfig KeepJobFlowAliveWhenNoSteps
    parameter is set to TRUE, the cluster transitions to the WAITING state rather than shutting down after the steps
    have completed.  For additional protection, you can set the JobFlowInstancesConfig TerminationProtected
    parameter to TRUE to lock the cluster and prevent it from being terminated by API call, user intervention, or in
    the event of a job flow error. A maximum of 256 steps are allowed in each job flow. If your cluster is long-
    running (such as a Hive data warehouse) or complex, you may require more than 256 steps to process your data.
    You can bypass the 256-step limitation in various ways, including using the SSH shell to connect to the master
    node and submitting queries directly to the software running on the master node, such as Hive and Hadoop. For
    more information on how to do this, see Add More than 256 Steps to a Cluster in the Amazon EMR Management Guide.
    For long running clusters, we recommend that you periodically store your results.  The instance fleets
    configuration is available only in Amazon EMR versions 4.8.0 and later, excluding 5.0.x versions. The RunJobFlow
    request can contain InstanceFleets parameters or InstanceGroups parameters, but not both.

    Args:
        name(Text): The name of the job flow.
        log_uri(Text, optional): The location in Amazon S3 to write the log files of the job flow. If a value is not provided,
            logs are not created. Defaults to None.
        log_encryption_kms_key_id(Text, optional): The KMS key used for encrypting log files. If a value is not provided, the logs remain encrypted
            by AES-256. This attribute is only available with Amazon EMR version 5.30.0 and later, excluding
            Amazon EMR 6.0.0. Defaults to None.
        additional_info(Text, optional): A JSON string for selecting additional features. Defaults to None.
        ami_version(Text, optional): Applies only to Amazon EMR AMI versions 3.x and 2.x. For Amazon EMR releases 4.0 and later,
            ReleaseLabel is used. To specify a custom AMI, use CustomAmiID. Defaults to None.
        release_label(Text, optional): The Amazon EMR release label, which determines the version of open-source application packages
            installed on the cluster. Release labels are in the form emr-x.x.x, where x.x.x is an Amazon EMR
            release version such as emr-5.14.0. For more information about Amazon EMR release versions and
            included application versions and features, see
            https://docs.aws.amazon.com/emr/latest/ReleaseGuide/. The release label applies only to Amazon
            EMR releases version 4.0 and later. Earlier versions use AmiVersion. Defaults to None.
        instances(Dict): A specification of the number and type of Amazon EC2 instances.
        steps(List, optional): A list of steps to run. Defaults to None.
        bootstrap_actions(List, optional): A list of bootstrap actions to run before Hadoop starts on the cluster nodes. Defaults to None.
        supported_products(List, optional):  For Amazon EMR releases 3.x and 2.x. For Amazon EMR releases 4.x and later, use Applications.
            A list of strings that indicates third-party software to use. For more information, see the
            Amazon EMR Developer Guide. Currently supported values are:   "mapr-m3" - launch the job flow
            using MapR M3 Edition.   "mapr-m5" - launch the job flow using MapR M5 Edition. Defaults to None.
        new_supported_products(List, optional):  For Amazon EMR releases 3.x and 2.x. For Amazon EMR releases 4.x and later, use Applications.
            A list of strings that indicates third-party software to use with the job flow that accepts a
            user argument list. EMR accepts and forwards the argument list to the corresponding installation
            script as bootstrap action arguments. For more information, see "Launch a Job Flow on the MapR
            Distribution for Hadoop" in the Amazon EMR Developer Guide. Supported values are:   "mapr-m3" -
            launch the cluster using MapR M3 Edition.   "mapr-m5" - launch the cluster using MapR M5
            Edition.   "mapr" with the user arguments specifying "--edition,m3" or "--edition,m5" - launch
            the job flow using MapR M3 or M5 Edition respectively.   "mapr-m7" - launch the cluster using
            MapR M7 Edition.   "hunk" - launch the cluster with the Hunk Big Data Analytics Platform.
            "hue"- launch the cluster with Hue installed.   "spark" - launch the cluster with Apache Spark
            installed.   "ganglia" - launch the cluster with the Ganglia Monitoring System installed. Defaults to None.
        applications(List, optional): Applies to Amazon EMR releases 4.0 and later. A case-insensitive list of applications for Amazon
            EMR to install and configure when launching the cluster. For a list of applications available
            for each Amazon EMR release version, see the Amazon EMR Release Guide. Defaults to None.
        configurations(List, optional): For Amazon EMR releases 4.0 and later. The list of configurations supplied for the EMR cluster
            you are creating. Defaults to None.
        visible_to_all_users(bool, optional): Set this value to true so that IAM principals in the account associated with the cluster can
            perform EMR actions on the cluster that their IAM policies allow. This value defaults to true
            for clusters created using the EMR API or the CLI create-cluster command. When set to false,
            only the IAM principal that created the cluster and the account root user can perform EMR
            actions for the cluster, regardless of the IAM permissions policies attached to other IAM
            principals. For more information, see Understanding the EMR Cluster VisibleToAllUsers Setting in
            the Amazon EMRManagement Guide. Defaults to None.
        job_flow_role(Text, optional): Also called instance profile and EC2 role. An IAM role for an EMR cluster. The EC2 instances of
            the cluster assume this role. The default role is EMR_EC2_DefaultRole. In order to use the
            default role, you must have already created it using the CLI or console. Defaults to None.
        service_role(Text, optional): The IAM role that will be assumed by the Amazon EMR service to access Amazon Web Services
            resources on your behalf. Defaults to None.
        tags(List, optional): A list of tags to associate with a cluster and propagate to Amazon EC2 instances. Defaults to None.
        security_configuration(Text, optional): The name of a security configuration to apply to the cluster. Defaults to None.
        auto_scaling_role(Text, optional): An IAM role for automatic scaling policies. The default role is EMR_AutoScaling_DefaultRole. The
            IAM role provides permissions that the automatic scaling feature requires to launch and
            terminate EC2 instances in an instance group. Defaults to None.
        scale_down_behavior(Text, optional): Specifies the way that individual Amazon EC2 instances terminate when an automatic scale-in
            activity occurs or an instance group is resized. TERMINATE_AT_INSTANCE_HOUR indicates that
            Amazon EMR terminates nodes at the instance-hour boundary, regardless of when the request to
            terminate the instance was submitted. This option is only available with Amazon EMR 5.1.0 and
            later and is the default for clusters created using that version. TERMINATE_AT_TASK_COMPLETION
            indicates that Amazon EMR adds nodes to a deny list and drains tasks from nodes before
            terminating the Amazon EC2 instances, regardless of the instance-hour boundary. With either
            behavior, Amazon EMR removes the least active nodes first and blocks instance termination if it
            could lead to HDFS corruption. TERMINATE_AT_TASK_COMPLETION available only in Amazon EMR version
            4.1.0 and later, and is the default for versions of Amazon EMR earlier than 5.1.0. Defaults to None.
        custom_ami_id(Text, optional): Available only in Amazon EMR version 5.7.0 and later. The ID of a custom Amazon EBS-backed Linux
            AMI. If specified, Amazon EMR uses this AMI when it launches cluster EC2 instances. For more
            information about custom AMIs in Amazon EMR, see Using a Custom AMI in the Amazon EMR Management
            Guide. If omitted, the cluster uses the base Linux AMI for the ReleaseLabel specified. For
            Amazon EMR versions 2.x and 3.x, use AmiVersion instead. For information about creating a custom
            AMI, see Creating an Amazon EBS-Backed Linux AMI in the Amazon Elastic Compute Cloud User Guide
            for Linux Instances. For information about finding an AMI ID, see Finding a Linux AMI. Defaults to None.
        ebs_root_volume_size(int, optional): The size, in GiB, of the Amazon EBS root device volume of the Linux AMI that is used for each
            EC2 instance. Available in Amazon EMR version 4.x and later. Defaults to None.
        repo_upgrade_on_boot(Text, optional): Applies only when CustomAmiID is used. Specifies which updates from the Amazon Linux AMI package
            repositories to apply automatically when the instance boots using the AMI. If omitted, the
            default is SECURITY, which indicates that only security updates are applied. If NONE is
            specified, no updates are applied, and all updates must be applied manually. Defaults to None.
        kerberos_attributes(Dict, optional): Attributes for Kerberos configuration when Kerberos authentication is enabled using a security
            configuration. For more information see Use Kerberos Authentication in the Amazon EMR Management
            Guide. Defaults to None.
        step_concurrency_level(int, optional): Specifies the number of steps that can be executed concurrently. The default value is 1. The
            maximum value is 256. Defaults to None.
        managed_scaling_policy(Dict, optional):  The specified managed scaling policy for an Amazon EMR cluster. Defaults to None.
        placement_group_configs(List, optional): The specified placement group configuration for an Amazon EMR cluster. Defaults to None.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_present:
              aws_auto.emr.job_flow.present:
                - name: value
                - instances: value
    '''
    
    result = dict(comment="", changes= None, name=name, result=True)
    ret = await hub.exec.boto3.client.emr.job_flow.id(
        ctx,
        jmes_path=name
    )
    if ret["status"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]
    

    
    before = await hub.exec.boto3.client.emr.describe_job_flows(name)

    if before:
        result["comment"] = f"'{name}' already exists"
    else:
        try:
            ret = await hub.exec.boto3.client.emr.run_job_flow(
                ctx,
                
                
                **{"Name": name, "LogUri": log_uri, "LogEncryptionKmsKeyId": log_encryption_kms_key_id, "AdditionalInfo": additional_info, "AmiVersion": ami_version, "ReleaseLabel": release_label, "Instances": instances, "Steps": steps, "BootstrapActions": bootstrap_actions, "SupportedProducts": supported_products, "NewSupportedProducts": new_supported_products, "Applications": applications, "Configurations": configurations, "VisibleToAllUsers": visible_to_all_users, "JobFlowRole": job_flow_role, "ServiceRole": service_role, "Tags": tags, "SecurityConfiguration": security_configuration, "AutoScalingRole": auto_scaling_role, "ScaleDownBehavior": scale_down_behavior, "CustomAmiId": custom_ami_id, "EbsRootVolumeSize": ebs_root_volume_size, "RepoUpgradeOnBoot": repo_upgrade_on_boot, "KerberosAttributes": kerberos_attributes, "StepConcurrencyLevel": step_concurrency_level, "ManagedScalingPolicy": managed_scaling_policy, "PlacementGroupConfigs": placement_group_configs}
            )
            result["result"] = ret["status"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            ret["comment"] = f"Created '{name}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"

    
    # TODO perform other modifications as needed here
    ...

    after = await hub.exec.boto3.client.emr.describe_job_flows(name)
    result["changes"] = differ.deep_diff(before, after)
    return result

async def absent(hub, ctx, name: Text, job_flow_ids: List)  -> Dict[str, Any]:
    r'''
    **Autogenerated function**
    
    TerminateJobFlows shuts a list of clusters (job flows) down. When a job flow is shut down, any step not yet
    completed is canceled and the EC2 instances on which the cluster is running are stopped. Any log files not
    already saved are uploaded to Amazon S3 if a LogUri was specified when the cluster was created. The maximum
    number of clusters allowed is 10. The call to TerminateJobFlows is asynchronous. Depending on the configuration
    of the cluster, it may take up to 1-5 minutes for the cluster to completely terminate and release allocated
    resources, such as Amazon EC2 instances.

    Args:
        name(Text): A name, ID, or JMES search path to identify the resource.
        job_flow_ids(List): A list of job flows to be shut down.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_absent:
              aws_auto.emr.job_flow.absent:
                - name: value
                - job_flow_ids: value
    '''
    
    result = dict(comment="", changes= None, name=name, result=True)
    ret = await hub.exec.boto3.client.emr.job_flow.id(
        ctx,
        jmes_path=name
    )
    if ret["status"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]
    

    

    before = await hub.exec.boto3.client.emr.describe_job_flows(name)

    if not before:
        result["comment"] = f"'{name}' already absent"
    else:
        try:
            ret = await hub.exec.boto3.client.emr.terminate_job_flows(
                ctx,
                
                
                **{"JobFlowIds": job_flow_ids}
            )
            result["result"] = ret["status"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            result["comment"] = f"Deleted '{name}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"

    

    after = await hub.exec.boto3.client.emr.describe_job_flows(name)
    result["changes"] = differ.deep_diff(before, after)
    return result

