U
    W+dq                     @   s   d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ G d	d
 d
eZdS )z,
Represents a connection to the EMR service
    N)
RegionInfo)AddInstanceGroupsResponseBootstrapActionListClusterClusterSummaryList
HadoopStepInstanceGroupListInstanceListJobFlowJobFlowStepListModifyInstanceGroupsResponseRunJobFlowResponseStepSummaryList)JarStep)AWSQueryConnection)EmrResponseError)sixc                       s~  e Zd ZejdddZejdddZejdddZe	Z
dZd	ZdP fdd	Zdd Zdd Zdd ZdQddZdd ZdRddZdSddZdTddZdUd d!ZdVd"d#Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd
d
d
d2d2d3d4d5d5d
d
g d
d
d
d
d
d
d
fd6d7Zd8d9 Z d:d; Z!d<d= Z"d>d? Z#d@dA Z$dBdC Z%dDdE Z&dFdG Z'dHdI Z(dJdK Z)dLdM Z*dNdO Z+  Z,S )WEmrConnectionZBotoZemr_versionz
2009-03-31Zemr_region_namez	us-east-1Zemr_region_endpointz(elasticmapreduce.us-east-1.amazonaws.comzHs3://{region_name}.elasticmapreduce/libs/script-runner/script-runner.jarz?s3://{region_name}.elasticmapreduce/libs/state-pusher/0.1/fetchNTr   /c                    s`   |st | | j| j}|| _tt| j||||||||| jj|	|
||||d | jj| _	d| _
d S )N)validate_certsprofile_nameZelasticmapreduce)r   DefaultRegionNameDefaultRegionEndpointregionsuperr   __init__ZendpointnameZauth_region_nameZauth_service_name)selfZaws_access_key_idZaws_secret_access_keyZ	is_secureportproxyZ
proxy_portZ
proxy_userZ
proxy_passdebugZhttps_connection_factoryr   pathZsecurity_tokenr   r   	__class__ 7/tmp/pip-unpacked-wheel-dlxw5sjy/boto/emr/connection.pyr   9   s.          
zEmrConnection.__init__c                 C   s   dgS )Nzhmac-v4r$   r   r$   r$   r%   _required_auth_capabilityT   s    z'EmrConnection._required_auth_capabilityc                 C   s   d|i}|  d|tS )z
        Describes an Elastic MapReduce cluster

        :type cluster_id: str
        :param cluster_id: The cluster id of interest
        	ClusterIdZDescribeCluster)
get_objectr   )r   
cluster_idparamsr$   r$   r%   describe_clusterW   s     zEmrConnection.describe_clusterc                 C   s   | j |gd}|r|d S dS )aD  
        This method is deprecated. We recommend you use list_clusters,
        describe_cluster, list_steps, list_instance_groups and
        list_bootstrap_actions instead.

        Describes a single Elastic MapReduce job flow

        :type jobflow_id: str
        :param jobflow_id: The job flow id of interest
        )jobflow_idsr   N)describe_jobflows)r   
jobflow_idZjobflowsr$   r$   r%   describe_jobflowc   s    zEmrConnection.describe_jobflowc                 C   sh   i }|r|  ||d |r(|  ||d |r>|tjj|d< |rT|tjj|d< | d|dtfgS )a}  
        This method is deprecated. We recommend you use list_clusters,
        describe_cluster, list_steps, list_instance_groups and
        list_bootstrap_actions instead.

        Retrieve all the Elastic MapReduce job flows on your account

        :type states: list
        :param states: A list of strings with job flow states wanted

        :type jobflow_ids: list
        :param jobflow_ids: A list of job flow IDs
        :type created_after: datetime
        :param created_after: Bound on job flow creation time

        :type created_before: datetime
        :param created_before: Bound on job flow creation time
        zJobFlowStates.memberJobFlowIds.memberCreatedAfterCreatedBeforeZDescribeJobFlowsmember)build_list_paramsstrftimebotoutilsISO8601Zget_listr
   )r   Zstatesr-   created_aftercreated_beforer+   r$   r$   r%   r.   r   s    zEmrConnection.describe_jobflowsc                 C   s   ||d}|  d|tS )z
        Describe an Elastic MapReduce step

        :type cluster_id: str
        :param cluster_id: The cluster id of interest
        :type step_id: str
        :param step_id: The step id of interest
        )r(   ZStepIdZDescribeStep)r)   r   )r   r*   Zstep_idr+   r$   r$   r%   describe_step   s    
zEmrConnection.describe_stepc                 C   s"   d|i}|r||d< |  d|tS )z
        Get a list of bootstrap actions for an Elastic MapReduce cluster

        :type cluster_id: str
        :param cluster_id: The cluster id of interest
        :type marker: str
        :param marker: Pagination marker
        r(   MarkerZListBootstrapActions)r)   r   r   r*   markerr+   r$   r$   r%   list_bootstrap_actions   s    
 z$EmrConnection.list_bootstrap_actionsc                 C   s\   i }|r| tjj|d< |r0| tjj|d< |r<||d< |rN| ||d | d|tS )a  
        List Elastic MapReduce clusters with optional filtering

        :type created_after: datetime
        :param created_after: Bound on cluster creation time
        :type created_before: datetime
        :param created_before: Bound on cluster creation time
        :type cluster_states: list
        :param cluster_states: Bound on cluster states
        :type marker: str
        :param marker: Pagination marker
        r2   r3   r=   zClusterStates.memberZListClusters)r6   r7   r8   r9   r5   r)   r   )r   r:   r;   Zcluster_statesr?   r+   r$   r$   r%   list_clusters   s    zEmrConnection.list_clustersc                 C   s"   d|i}|r||d< |  d|tS )z
        List EC2 instance groups in a cluster

        :type cluster_id: str
        :param cluster_id: The cluster id of interest
        :type marker: str
        :param marker: Pagination marker
        r(   r=   ZListInstanceGroups)r)   r   r>   r$   r$   r%   list_instance_groups   s    
 z"EmrConnection.list_instance_groupsc                 C   s@   d|i}|r||d< |r ||d< |r2|  ||d | d|tS )a  
        List EC2 instances in a cluster

        :type cluster_id: str
        :param cluster_id: The cluster id of interest
        :type instance_group_id: str
        :param instance_group_id: The EC2 instance group id of interest
        :type instance_group_types: list
        :param instance_group_types: Filter by EC2 instance group type
        :type marker: str
        :param marker: Pagination marker
        r(   ZInstanceGroupIdr=   zInstanceGroupTypes.memberZListInstances)r5   r)   r	   )r   r*   Zinstance_group_idZinstance_group_typesr?   r+   r$   r$   r%   list_instances   s     zEmrConnection.list_instancesc                 C   s4   d|i}|r||d< |r&|  ||d | d|tS )a  
        List cluster steps

        :type cluster_id: str
        :param cluster_id: The cluster id of interest
        :type step_states: list
        :param step_states: Filter by step states
        :type marker: str
        :param marker: Pagination marker
        r(   r=   zStepStates.memberZ	ListSteps)r5   r)   r   )r   r*   Zstep_statesr?   r+   r$   r$   r%   
list_steps  s     zEmrConnection.list_stepsc                 C   s8   t |tjstd|i}|| | | jd|ddS )a  
        Create new metadata tags for the specified resource id.

        :type resource_id: str
        :param resource_id: The cluster id

        :type tags: dict
        :param tags: A dictionary containing the name/value pairs.
                     If you want to create only a tag name, the
                     value for that tag should be the empty string
                     (e.g. '') or None.
        
ResourceIdZAddTagsPOSTZverb)
isinstancer   string_typesAssertionErrorupdate_build_tag_list
get_statusr   Zresource_idtagsr+   r$   r$   r%   add_tags  s     zEmrConnection.add_tagsc                 C   s*   d|i}| | d| | jd|ddS )z
        Remove metadata tags for the specified resource id.

        :type resource_id: str
        :param resource_id: The cluster id

        :type tags: list
        :param tags: A list of tag names to remove.
        rE   ZTagKeysZ
RemoveTagsrF   rG   )rK   _build_string_listrM   rN   r$   r$   r%   remove_tags.  s
     zEmrConnection.remove_tagsc                 C   s   |  |g dS )z
        Terminate an Elastic MapReduce job flow

        :type jobflow_id: str
        :param jobflow_id: A jobflow id
        N)terminate_jobflows)r   r/   r$   r$   r%   terminate_jobflow>  s    zEmrConnection.terminate_jobflowc                 C   s"   i }|  ||d | jd|ddS )z
        Terminate an Elastic MapReduce job flow

        :type jobflow_ids: list
        :param jobflow_ids: A list of job flow IDs
        r1   ZTerminateJobFlowsrF   rG   )r5   rM   )r   r-   r+   r$   r$   r%   rS   G  s    z EmrConnection.terminate_jobflowsc                    sP   t |ts|g}i }||d<  fdd|D }| |  jd|tddS )z
        Adds steps to a jobflow

        :type jobflow_id: str
        :param jobflow_id: The job flow id
        :type steps: list(boto.emr.Step)
        :param steps: A list of steps to add to the job
        	JobFlowIdc                    s   g | ]}  |qS r$   _build_step_args.0stepr&   r$   r%   
<listcomp>a  s     z3EmrConnection.add_jobflow_steps.<locals>.<listcomp>ZAddJobFlowStepsrF   rG   )rH   listrK   _build_step_listr)   r   )r   r/   stepsr+   	step_argsr$   r&   r%   add_jobflow_stepsR  s    	
   zEmrConnection.add_jobflow_stepsc                 C   s>   t |ts|g}i }||d< || | | jd|tddS )aI  
        Adds instance groups to a running cluster.

        :type jobflow_id: str
        :param jobflow_id: The id of the jobflow which will take the
            new instance groups

        :type instance_groups: list(boto.emr.InstanceGroup)
        :param instance_groups: A list of instance groups to add to the job
        rU   ZAddInstanceGroupsrF   rG   )rH   r\   rK   _build_instance_group_list_argsr)   r   )r   r/   instance_groupsr+   r$   r$   r%   add_instance_groupsg  s    
 z!EmrConnection.add_instance_groupsc                 C   sz   t |ts|g}t |ts |g}t||}i }t|D ]0\}}|d |d|d  < |d |d|d  < q6| jd|tddS )ah  
        Modify the number of nodes and configuration settings in an
        instance group.

        :type instance_group_ids: list(str)
        :param instance_group_ids: A list of the ID's of the instance
            groups to be modified

        :type new_sizes: list(int)
        :param new_sizes: A list of the new sizes for each instance group
        r   z(InstanceGroups.member.%d.InstanceGroupId   z&InstanceGroups.member.%d.InstanceCountZModifyInstanceGroupsrF   rG   )rH   r\   zip	enumerater)   r   )r   Zinstance_group_idsZ	new_sizesrb   r+   kZigr$   r$   r%   modify_instance_groups{  s    


 z$EmrConnection.modify_instance_groupszm1.smallrd   TERMINATE_JOB_FLOWFc                    s  |pg }i }|r||d< |r$||d< ||d<   |||	|}|| |sd |||}|| n, |}tdd t|D }|| |
rtddd jj	 j
jd	 jj	 j
jd	d
}|d| |r fdd|D }| | |r fdd|D }| | |r*||d< |dk	r<||d< |rxt|D ]*\}}|dkrl||d n|||< qL|dk	r|rd|d< nd|d< |dk	r||d< |dk	r||d<  jd|tdd}|jS )a  
        Runs a job flow
        :type name: str
        :param name: Name of the job flow

        :type log_uri: str
        :param log_uri: URI of the S3 bucket to place logs

        :type ec2_keyname: str
        :param ec2_keyname: EC2 key used for the instances

        :type availability_zone: str
        :param availability_zone: EC2 availability zone of the cluster

        :type master_instance_type: str
        :param master_instance_type: EC2 instance type of the master

        :type slave_instance_type: str
        :param slave_instance_type: EC2 instance type of the slave nodes

        :type num_instances: int
        :param num_instances: Number of instances in the Hadoop cluster

        :type action_on_failure: str
        :param action_on_failure: Action to take if a step terminates

        :type keep_alive: bool
        :param keep_alive: Denotes whether the cluster should stay
            alive upon completion

        :type enable_debugging: bool
        :param enable_debugging: Denotes whether AWS console debugging
            should be enabled.

        :type hadoop_version: str
        :param hadoop_version: Version of Hadoop to use. This no longer
            defaults to '0.20' and now uses the AMI default.

        :type steps: list(boto.emr.Step)
        :param steps: List of steps to add with the job

        :type bootstrap_actions: list(boto.emr.BootstrapAction)
        :param bootstrap_actions: List of bootstrap actions that run
            before Hadoop starts.

        :type instance_groups: list(boto.emr.InstanceGroup)
        :param instance_groups: Optional list of instance groups to
            use when creating this job.
            NB: When provided, this argument supersedes num_instances
            and master/slave_instance_type.

        :type ami_version: str
        :param ami_version: Amazon Machine Image (AMI) version to use
            for instances. Values accepted by EMR are '1.0', '2.0', and
            'latest'; EMR currently defaults to '1.0' if you don't set
            'ami_version'.

        :type additional_info: JSON str
        :param additional_info: A JSON string for selecting additional features

        :type api_params: dict
        :param api_params: a dictionary of additional parameters to pass
            directly to the EMR API (so you don't have to upgrade boto to
            use new EMR features). You can also delete an API parameter
            by setting it to None.

        :type visible_to_all_users: bool
        :param visible_to_all_users: Whether the job flow is visible to all IAM
            users of the AWS account associated with the job flow. If this
            value is set to ``True``, all IAM users of that AWS
            account can view and (if they have the proper policy permissions
            set) manage the job flow. If it is set to ``False``, only
            the IAM user that created the job flow can view and manage
            it.

        :type job_flow_role: str
        :param job_flow_role: An IAM role for the job flow. The EC2
            instances of the job flow assume this role. The default role is
            ``EMRJobflowDefault``. In order to use the default role,
            you must have already created it using the CLI.

        :type service_role: str
        :param service_role: The IAM role that will be assumed by the Amazon
            EMR service to access AWS resources on your behalf.

        :rtype: str
        :return: The jobflow id
        ActionOnFailureZLogUriNamec                 s   s   | ]\}}d | |fV  qdS )zInstances.%sNr$   )rY   rg   vr$   r$   r%   	<genexpr>  s    z,EmrConnection.run_jobflow.<locals>.<genexpr>zSetup Hadoop Debuggingri   N)Zregion_name)r   action_on_failure
main_classjarr_   r   c                    s   g | ]}  |qS r$   rV   rX   r&   r$   r%   r[   /  s     z-EmrConnection.run_jobflow.<locals>.<listcomp>c                    s   g | ]}  |qS r$   )_build_bootstrap_action_args)rY   bootstrap_actionr&   r$   r%   r[   3  s     Z
AmiVersionZAdditionalInfotrueVisibleToAllUsersfalseZJobFlowRoleZServiceRoleZ
RunJobFlowrF   rG   )_build_instance_common_argsrK   #_build_instance_count_and_type_argsra   dictr   	iteritemsr   DebuggingJarformatr   r   DebuggingArgsinsertr]   _build_bootstrap_action_listpopr)   r   Z	jobflowid)r   r   Zlog_uriec2_keynameavailability_zonemaster_instance_typeslave_instance_typenum_instancesrn   
keep_aliveZenable_debugginghadoop_versionr^   bootstrap_actionsrb   Zadditional_infoZami_versionZ
api_paramsZvisible_to_all_usersZjob_flow_roleZservice_roler+   Zcommon_paramsZinstance_paramsZ	list_argsZdebugging_stepr_   Zbootstrap_action_argskeyvalueresponser$   r&   r%   run_jobflow  s~    h








   zEmrConnection.run_jobflowc                 C   s@   |dkst i }|rdpd|d< | ||gd | jd|ddS )	a/  
        Set termination protection on specified Elastic MapReduce job flows

        :type jobflow_ids: list or str
        :param jobflow_ids: A list of job flow IDs

        :type termination_protection_status: bool
        :param termination_protection_status: Termination protection status
        TFrs   ru   ZTerminationProtectedr1   ZSetTerminationProtectionrF   rG   rJ   r5   rM   )r   r/   Ztermination_protection_statusr+   r$   r$   r%   set_termination_protectionS  s
    z(EmrConnection.set_termination_protectionc                 C   s@   |dkst i }|rdpd|d< | ||gd | jd|ddS )	a  
        Set whether specified Elastic Map Reduce job flows are visible to all IAM users

        :type jobflow_ids: list or str
        :param jobflow_ids: A list of job flow IDs

        :type visibility: bool
        :param visibility: Visibility
        r   rs   ru   rt   r1   ZSetVisibleToAllUsersrF   rG   r   )r   r/   Z
visibilityr+   r$   r$   r%   set_visible_to_all_usersf  s
    
z&EmrConnection.set_visible_to_all_usersc                 C   sP   i }|j |d< z|j|d< W n tk
r0   Y nX | }|rL| ||d |S )NzScriptBootstrapAction.Pathrk   z!ScriptBootstrapAction.Args.member)r!   r   AttributeErrorargsr5   )r   rr   Zbootstrap_action_paramsr   r$   r$   r%   rq   x  s    
z*EmrConnection._build_bootstrap_action_argsc                 C   sV   i }|j |d< | |d< | }|r.||d< | }|rH| ||d |j|d< |S )Nrj   zHadoopJarStep.JarzHadoopJarStep.MainClasszHadoopJarStep.Args.memberrk   )rn   rp   ro   r   r5   r   )r   rZ   Zstep_paramsro   r   r$   r$   r%   rW     s    

zEmrConnection._build_step_argsc                 C   sR   t |ts|g}i }t|D ]0\}}t|D ]\}}||d|d |f < q.q|S )NzBootstrapActions.member.%s.%srd   rH   r\   rf   r   ry   )r   r   r+   irr   r   r   r$   r$   r%   r~     s    
z*EmrConnection._build_bootstrap_action_listc                 C   sR   t |ts|g}i }t|D ]0\}}t|D ]\}}||d|d |f < q.q|S )NzSteps.member.%s.%srd   r   )r   r^   r+   r   rZ   r   r   r$   r$   r%   r]     s    
zEmrConnection._build_step_listc                 C   s>   t |ts|g}i }t|D ]\}}||d||d f < q|S )Nz%s.member.%srd   )rH   r\   rf   )r   fielditemsr+   r   itemr$   r$   r%   rQ     s    
z EmrConnection._build_string_listc                 C   sb   t |tsti }ttt|ddD ]4\}}|\}}d| }||d| < |r(||d| < q(|S )Nrd   )startzTags.member.%sz%s.Keyz%s.Value)rH   rx   rJ   rf   sortedr   ry   )r   rO   r+   r   	key_valuer   r   Zcurrent_prefixr$   r$   r%   rL     s    zEmrConnection._build_tag_listc                 C   s8   dt | i}|r||d< |r(||d< |r4||d< |S )z
        Takes a number of parameters used when starting a jobflow (as
        specified in run_jobflow() above). Returns a comparable dict for
        use in making a RunJobFlow request.
        z%Instances.KeepJobFlowAliveWhenNoStepszInstances.HadoopVersionzInstances.Ec2KeyNamez$Instances.Placement.AvailabilityZone)strlower)r   r   r   r   r   r+   r$   r$   r%   rv     s     
z)EmrConnection._build_instance_common_argsc                 C   s   |||d}|S )z
        Takes a master instance type (string), a slave instance type
        (string), and a number of instances. Returns a comparable dict
        for use in making a RunJobFlow request.
        )zInstances.MasterInstanceTypezInstances.SlaveInstanceTypezInstances.InstanceCountr$   )r   r   r   r   r+   r$   r$   r%   rw     s
    z1EmrConnection._build_instance_count_and_type_argsc                 C   s2   |j |j|j|j|jd}|jdkr.|j|d< |S )z
        Takes an InstanceGroup; returns a dict that, when its keys are
        properly prefixed, can be used for describing InstanceGroups in
        RunJobFlow or AddInstanceGroups requests.
        )ZInstanceCountZInstanceRoleZInstanceTyperk   ZMarketZSPOTZBidPrice)r   roletyper   ZmarketZbidprice)r   instance_groupr+   r$   r$   r%   _build_instance_group_args  s    

z(EmrConnection._build_instance_group_argsc                 C   s\   t |ts|g}i }t|D ]:\}}| |}t|D ]\}}||d|d |f < q8q|S )z
        Takes a list of InstanceGroups, or a single InstanceGroup. Returns
        a comparable dict for use in making a RunJobFlow or AddInstanceGroups
        request.
        zInstanceGroups.member.%d.%srd   )rH   r\   rf   r   r   ry   )r   rb   r+   r   r   Zig_dictr   r   r$   r$   r%   ra     s    

z-EmrConnection._build_instance_group_list_args)NNTNNNNNr   NNr   NTN)NNNN)N)NNNN)N)NNN)NN)-__name__
__module____qualname__r7   configgetZ
APIVersionr   r   r   ResponseErrorrz   r|   r   r'   r,   r0   r.   r<   r@   rA   rB   rC   rD   rP   rR   rT   rS   r`   rc   rh   r   r   r   rq   rW   r~   r]   rQ   rL   rv   rw   r   ra   __classcell__r$   r$   r"   r%   r   +   s   
                           
#
    

    

	  
 ;

	r   )__doc__typesr7   Z
boto.utilsZboto.ec2.regioninfor   Zboto.emr.emrobjectr   r   r   r   r   r   r	   r
   r   r   r   r   Zboto.emr.stepr   Zboto.connectionr   Zboto.exceptionr   Zboto.compatr   r   r$   r$   r$   r%   <module>   s   8