
                         ~   d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZddl	Z	ddl
mZ ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZdZdZdZd Z d Z!d Z"d#dZ# G d d      Z$ G d d      Z% G d d      Z& G d d      Z' G d d       Z( G d! d"      Z)y)$z4Helpers for interacting with the Cloud Dataflow API.    )absolute_import)division)unicode_literalsN)encoding)
exceptions)cloudbuild_util)storage_api)storage_util)apis)submit_util)log)
properties)filesdataflowv1b3zus-central1c                  >    t        j                  t        t              S N)r   GetMessagesModuleDATAFLOW_API_NAMEDATAFLOW_API_VERSION     +lib/googlecloudsdk/api_lib/dataflow/apis.pyr   r   .       			 13G	HHr   c                  >    t        j                  t        t              S r   )r   GetClientInstancer   r   r   r   r   r   r   2   r   r   c                  j    t         j                  j                  j                  j	                  d      S )NT)required)r   VALUEScoreprojectGetr   r   r   
GetProjectr#   6   s(    						'	'	+	+T	+	::r   c                     |sd|  dS d|  dS )z/Returns full the image path of the given image.zgcr.io/dataflow-templates-base/z-template-launcher-base:latestz)-template-launcher-base-distroless:latestr   )imageis_distrolesss     r   _GetBaseImagePathr'   :   s)    	
)%0NO +5'1Z	[[r   c                   ,   e Zd ZdZ e       j
                  Z e       j                  Z e       j                  Z
 e       j                  Zed        Zed
d       Zedd       Ze	 	 	 	 	 	 dd       Zedd       Ze	 	 dd       Ze	 	 	 	 dd	       Zy)Jobsz'The Jobs set of Dataflow API functions.c                  *    t               j                  S r   r   projects_locations_jobsr   r   r   
GetServicezJobs.GetServiceM       666r   Nc                    |xs
 t               }|xs t        }t               j                  | |||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)aW  Calls the Dataflow Jobs.Get method.

    Args:
      job_id: Identifies a single job.
      project_id: The project which owns the job.
      region_id: The regional endpoint where the job lives.
      view: (DataflowProjectsJobsGetRequest.ViewValueValuesEnum) Level of
        information requested in response.

    Returns:
      (Job)
    )jobIdlocation	projectIdviewN)r#   DATAFLOW_API_DEFAULT_REGIONr   'DataflowProjectsLocationsJobsGetRequestr)   r-   r"   apitools_exceptions	HttpErrorr   HttpException)job_id
project_id	region_idr3   requesterrors         r   r"   zJobs.GetQ   s     +z|J88I!IIyJT J KG,__""7++(( ,$$U++,   "A B-BBc                 B   |xs
 t               }|xs t        }d}|rRt               j                  j	                  t               j                  j                  j                  dd      g      }t               j                  |t               j                  j                  j                        }t               j                  | |||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)a  Cancels a job by calling the Jobs.Update method.

    Args:
      job_id: Identifies a single job.
      force: True to forcibly cancel the job.
      project_id: The project which owns the job.
      region_id: The regional endpoint where the job lives.

    Returns:
      (Job)
    Nforce_cancel_jobtruekeyvalueadditionalProperties)labelsrequestedStater0   r1   r2   job)r#   r4   r   JobLabelsValueAdditionalPropertyRequestedStateValueValuesEnumJOB_STATE_CANCELLED*DataflowProjectsLocationsJobsUpdateRequestr)   r-   Updater6   r7   r   r8   )r9   forcer:   r;   rG   rJ   r<   r=   s           r   CancelzJobs.Canceli   s    +z|J88IF "&&22


!
!
-
-
@
@$F A 4I2 	f 

!
!)+//MM,, " /C  !LLyJC M IG,__%%g..(( ,$$U++,s   "C1 1DDDc                 "   |xs
 t               }|xs t        }t               j                  t               j	                  |||rdn|            }g }||j                  d       ||j                  d       ||r|j                  d       dj                  |      }	t               j                  | ||||	      }
	 t        j                         j                  |
      S # t        j                  $ r}t        j                  |      d}~ww xY w)	a0  Update pipeline options on a running job.

    You should specify at-least one (or both) of min_num_workers and
    max_num_workers.

    Args:
      job_id: ID of job to update
      project_id: Project of the job
      region_id: Region the job is in
      min_num_workers: Lower-bound for worker autoscaling
      max_num_workers: Upper-bound for worker autoscaling
      worker_utilization_hint: Target CPU utilization for worker autoscaling
      unset_worker_utilization_hint: Unsets worker_utilization_hint value

    Returns:
      The updated Job
    N)minNumWorkersmaxNumWorkersworkerUtilizationHint)runtimeUpdatableParamsz(runtime_updatable_params.min_num_workersz(runtime_updatable_params.max_num_workersz0runtime_updatable_params.worker_utilization_hint,)r0   r1   r2   rJ   
updateMask)r#   r4   r   rK   RuntimeUpdatableParamsappendjoinrP   r)   r-   rQ   r6   r7   r   r8   )r9   r:   r;   min_num_workersmax_num_workersworker_utilization_hintunset_worker_utilization_hintrJ   update_mask_piecesupdate_maskr<   r=   s               r   UpdateOptionszJobs.UpdateOptions   s&   8 +z|J88I


!
!02II)) 1 ,  J  
 " 
C " JK" JK+(
< ((-.K!LL M G,__%%g..(( ,$$U++,s   >"C! !D4D		Dc                    |xs
 t               }|xs t        }t               j                  t               j                  j                  j
                        }t               j                  | |||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)zDrains a job by calling the Jobs.Update method.

    Args:
      job_id: Identifies a single job.
      project_id: The project which owns the job.
      region_id: The regional endpoint where the job lives.

    Returns:
      (Job)
    )rH   rI   N)r#   r4   r   rK   rN   JOB_STATE_DRAINEDrP   r)   r-   rQ   r6   r7   r   r8   )r9   r:   r;   rJ   r<   r=   s         r   Drainz
Jobs.Drain   s     +z|J88I


!
!)+//MM** " -C  !LLyJC M IG,__%%g..(( ,$$U++,s   7"B C-CCc                 ~   |xs
 t               }|xs t        }t               j                  |g      }t               j	                  |      }t               j                  | |||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)aY  Resumes a job by calling the Jobs.Update method.

    Args:
      job_id: Identifies a single job.
      experiment_with_token: The resume token unique to the job prefixed with
        the experiment key.
      project_id: The project which owns the job.
      region_id: The regional endpoint where the job lives.

    Returns:
      (Job)
    )experiments)environmentrI   N)r#   r4   r   EnvironmentrK   rP   r)   r-   rQ   r6   r7   r   r8   )r9   experiment_with_tokenr:   r;   rj   rJ   r<   r=   s           r   ResumeUnsupportedSDKzJobs.ResumeUnsupportedSDK   s    " +z|J88I#%11*+ 2 -K


!
!k
!
:C!LLyJC M IG,__%%g..(( ,$$U++,s   ,"B B<"B77B<c           
      H   |xs
 t               }|xs t        }t               j                  | ||t               j	                  |||            }	 t
        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)ab  Takes a snapshot of a job via the Jobs.Snapshot method.

    Args:
      job_id: Identifies a single job.
      project_id: The project which owns the job.
      region_id: The regional endpoint where the job lives.
      ttl: The ttl for the snapshot.
      snapshot_sources: If true, the sources will be snapshotted.

    Returns:
      (Snapshot)
    )r1   ttlsnapshotSources)r0   r1   r2   snapshotJobRequestN)r#   r4   r   ,DataflowProjectsLocationsJobsSnapshotRequestSnapshotJobRequestr)   r-   Snapshotr6   r7   r   r8   )r9   r:   r;   ro   snapshot_sourcesr<   r=   s          r   rt   zJobs.Snapshot  s    $ +z|J88I!NN,.AAC9I B K	 O G,__''00(( ,$$U++,s   "A4 4B!BB!NNN)FNN)NNNNNN)NN)NN604800sF)__name__
__module____qualname____doc__r   r5   GET_REQUEST(DataflowProjectsLocationsJobsListRequestLIST_REQUEST%DataflowProjectsJobsAggregatedRequestAGGREGATED_LIST_REQUESTrP   UPDATE_REQUESTstaticmethodr-   r"   rS   rd   rg   rm   rt   r   r   r   r)   r)   C   s    /!#KK+"$MM,- )) $ ..  7 7 , ,. , ,@  "$(A, A,F , ,0  '+%), ,8  %	, ,r   r)   c                   T    e Zd ZdZ e       j
                  Zed        Zedd       Z	y)Metricsz*The Metrics set of Dataflow API functions.c                  *    t               j                  S r   r+   r   r   r   r-   zMetrics.GetService,  r.   r   Nc                    |xs
 t               }|xs t        }t               j                  | |||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)a  Calls the Dataflow Metrics.Get method.

    Args:
      job_id: The job to get messages for.
      project_id: The project which owns the job.
      region_id: The regional endpoint of the job.
      start_time: Return only metric data that has changed since this time.
        Default is to return all information about all metrics for the job.

    Returns:
      (MetricUpdate)
    )r0   r1   r2   	startTimeN)r#   r4   r   .DataflowProjectsLocationsJobsGetMetricsRequestr   r-   
GetMetricsr6   r7   r   r8   )r9   r:   r;   
start_timer<   r=   s         r   r"   zMetrics.Get0  s     +z|J88I 44	 5  ,!,,W55(( ,$$U++,r>   rv   )
rx   ry   rz   r{   r   r   r|   r   r-   r"   r   r   r   r   r   &  s@    2! 22  7 7 , ,r   r   c                       e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)TemplateArgumentsz%Wrapper class for template arguments.Nc                 p   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        y r   )r:   r;   job_namegcs_locationzonemax_workersnum_workersnetwork
subnetworkworker_machine_typelauncher_machine_typestaging_locationtemp_locationkms_key_namedisable_public_ips
parametersservice_account_emailworker_regionworker_zoneenable_streaming_engineadditional_experimentsadditional_pipeline_optionsadditional_user_labelsstreaming_updatetransform_name_mappingsflexrs_goal)selfr:   r;   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                              r   __init__zTemplateArguments.__init__k  s    6 !DODNDM$DDI"D"DDL DO2D!6D,D&D$D0D DO!6D&D"D#:D "8D'BD$"8D,D#:D "Dr   )NNNNNNNNNNNNNNNNNNNNNNNNNN)rx   ry   rz   r{   r:   r;   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   M  s    -*),(	$++'*-,*-+  $ +  #'%) $! "&%)!'+&*+/&* $'+54#r   r   c                      e Zd ZdZ e       j
                  Z e       j                  Zej                  Z
 e       j                  Zej                  Z e       j                  Zej                   Zej$                  Z e       j(                  Zej                  Zej.                  Z e       j                  j2                  Z e       j                  j6                  Z e       j:                  Z e       j>                  Z  e       j>                  jB                  Z" e       jF                  Z$ e%d      Z& e%d      Z' e%d      Z( e%dd      Z) e%dd      Z* e%dd      Z+ e%d      Z, e%d      Z- e%dd      Z.dZ/e0jb                  e0jd                  z  e0jf                  z  Z4e0jj                  e0jl                  z  e0jn                  z  e0jp                  z  Z9e0jb                  e0jt                  z  e0jn                  z  e0jv                  z  e0jp                  z  Z<e=d	        Z>e=d
        Z?e=d d       Z@e=d d       ZAe=d        ZBe=d        ZCe=d        ZDe=d        ZEe=d        ZFe=d        ZGe=d        ZHe=d        ZIe=d        ZJe=d        ZKe=d        ZLe=d        ZMe=d        ZNe=	 	 	 	 d!d       ZOe=d        ZPe=d        ZQe=d        ZRe=d d       ZSy)"	Templatesz,The Templates set of Dataflow API functions.java11java17java21Tpython3goz4gs://dataflow-templates-{}/latest/flex/Yaml_Templatec                  *    t               j                  S r   )r   projects_locations_templatesr   r   r   r-   zTemplates.GetService      ;;;r   c                  *    t               j                  S r   )r    projects_locations_flexTemplatesr   r   r   GetFlexTemplateServicez Templates.GetFlexTemplateService      ???r   Nc                 $   g }| j                   }|rt        j                  |      ni D ]5  \  }}|j                  t        j
                  j                  ||             7 | j                  xs t        }t               j                  j                  }|j                  }| j                  r|nd}t               j                  j                  }	t        j                  | j                   |	      }
t        j#                  | j$                  | j&                  |t               j                  | j(                  | j*                  | j,                  | j.                  | j0                  | j2                  | j4                  | j6                  | j8                  || j:                  | j<                  | j>                  |
r	 |	|
      nd| j@                  r| j@                  ng | jB                  r| jB                  ng       |rt        j                  |      nd      }t               jE                  | jF                  xs
 tI               ||      }	 t        jK                         jM                  |      S # tN        jP                  $ r}tS        jT                  |      d}~ww xY w)zCalls the Dataflow Templates.CreateFromJob method.

    Args:
      template_args: Arguments for create template.

    Returns:
      (Job)
    rB   NrE   )serviceAccountEmailr   
maxWorkers
numWorkersr   r   machineTypetempLocation
kmsKeyNameipConfigurationworkerRegion
workerZoneenableStreamingEngineadditionalUserLabelsadditionalExperimentsadditionalPipelineOptions)gcsPathjobNamer1   rj   r   )r2   r1   createJobFromTemplateRequest)+r   six	iteritemsr\   r   PARAMETERS_VALUErM   r;   r4   r   RuntimeEnvironmentIpConfigurationValueValuesEnumWORKER_IP_PRIVATEr   AdditionalUserLabelsValue _Templates__ConvertDictArgumentsr   CREATE_REQUESTr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   /DataflowProjectsLocationsTemplatesCreateRequestr:   r#   r-   Creater6   r7   r   r8   )template_argsparams_listr   kvr;   ip_configuration_enum
ip_privateip_configurationuser_labels_valueuser_labels_listbodyr<   r=   s                 r   r   zTemplates.Create  sn    K))J-7j)R?1

$
$
7
7AQ
7
GI @
 ''F+FI- 77 &88J%2%E%Ez4) 22  77,, ##**&&%':: - C C##$00$00!))$//%99&77$11,&44$00"/"G"G   "3%5"7%) !77 44 !<< 993 ; 8 2< --!, . .AEA $  GDB   55**:jl%) 6 + ,!!#**733(( ,$$U++,s   ?"I" "J5J

Jc                 &   g }| j                   }|rt        j                  |      ni D ]5  \  }}|j                  t        j
                  j                  ||             7 t        j                  | j                  t        j                        }d}d}| j                  r$| j                  }|rt        j                  |      }| j                  xs t        }t               j                  j                  }	|	j                   }
| j"                  r|
nd}t        j%                  t               j                  | j&                  | j(                  | j*                  | j,                  | j.                  | j0                  | j2                  | j4                  | j6                  || j8                  | j:                  | j<                  | j>                  r| j>                  ng       | j@                  |rt        j                  |      nd||      }t               jC                  | jD                  ||| jF                  xs
 tI               d      }	 t        jK                         jM                  |      S # tN        jP                  $ r}tS        jT                  |      d}~ww xY w)a  Calls the Dataflow Templates.LaunchTemplate method on a dynamic template.

    Args:
      template_args: Arguments to create template. gcs_location must point to a
        Json serialized DynamicTemplateFileSpec.

    Returns:
      (LaunchTemplateResponse)
    rB   NrE   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   )rj   r   r   updatetransformNameMappingF)r   r1   launchTemplateParametersr2   validateOnly)+r   r   r   r\   r    LAUNCH_TEMPLATE_PARAMETERS_VALUErM   r   r   -DYNAMIC_TEMPLATE_TRANSFORM_NAME_MAPPING_VALUEr   r;   r4   r   r   r   r   r   LAUNCH_TEMPLATE_PARAMETERSr   r   r   r   r   r   r   r   r   r   r   r   r   r   /DataflowProjectsLocationsTemplatesLaunchRequestr   r:   r#   r-   Launchr6   r7   r   r8   )r   r   r   r   r   transform_mapping_listtransform_mappingsr   r;   r   r   r   r   r<   r=   s                  r   LaunchDynamicTemplatezTemplates.LaunchDynamicTemplate&  sv    K))J-7j)R?1

4
4
G
G1 H  @
 '==--?? %%&77	CC%; D  	 ''F+FI- 77 &88J%2%E%Ez4//%':: - C C##$00$00!))$//%99&77$11,&44$00"/"G"G !77 44# ; 
( &&1< ==!, > .BF/3 0 D8 	KK!..%)#..>*, 	L 	
 ,!!#**733(( ,$$U++,s    "I# #J6JJc                     g }| r?t        j                  |       D ]'  \  }}|j                  |j                  ||             ) |S )zConvert dictionary arguments to parameter list .

    Args:
      arguments: Arguments for create job using template.
      value_message: the value message of the arguments

    Returns:
      List of value_message.AdditionalProperty
    rB   )r   r   r\   rM   )	argumentsvalue_messager   r   r   s        r   __ConvertDictArgumentsz Templates.__ConvertDictArgumentsy  sI     K--	*$!Q=;;;KL + r   c                    d}d}d|d<   t        |j                               D cg c]  \  }}dj                  ||       }}}dj                  |      }dj                  |      }	dj                  |	      }
t	        j
                  |      j                  t        j                  |       ||
dj                  |      	      }|S c c}}w )
aF  Builds Dockerfile contents for java flex template image.

    Args:
      flex_template_base_image: SDK version or base image to use.
      pipeline_paths: List of paths to pipelines and dependencies.
      env: Dictionary of env variables to set in the container image.

    Returns:
      Dockerfile contents as string.
    B
    FROM {base_image}

    {env}

    {copy}

    {commands}
     z/template/*FLEX_TEMPLATE_JAVA_CLASSPATH	ENV {}={}
 COPY {} /template/
base_imageenvcopycommands)sorteditemsformatr]   textwrapdedentr   _GetFlexTemplateBaseImage)flex_template_base_imagepipeline_pathsr   dockerfile_templater   r   r   envsenv_listpathscopy_commanddockerfile_contentss               r   BuildJavaImageDockerfilez"Templates.BuildJavaImageDockerfile  s     H*7C&'17		1DE1DAKq!$1DDEyyHHH^$E'..u5L"//*=>EE66$&8$ F &  Fs   Cc           	      
   d}g d}d|d    |d<   d|v ra|d   j                  d      }|rK|D cg c]  }d| 	 }}dj                  |      |d<   dj                  |      }|j                  d|        d	|v r3d|d	    |d	<   |j                  d
|d	           |j                  d       d|v rd|d    |d<   t        |j	                               D 	
cg c]  \  }	}
dj                  |	|
       }}	}
dj                  |      }dj                  |      }dj                  |      }t        j                  |      j                  t        j                  |       ||ddj                  |      z         }|S c c}w c c}
}	w )aH  Builds Dockerfile contents for python flex template image.

    Args:
      flex_template_base_image: SDK version or base image to use.
      pipeline_paths: List of paths to pipelines and dependencies.
      env: Dictionary of env variables to set in the container image.

    Returns:
      Dockerfile contents as string.
    r   )zapt-get updatez!apt-get install -y libffi-dev gitzrm -rf /var/lib/apt/lists/*z
/template/FLEX_TEMPLATE_PYTHON_PY_FILE#FLEX_TEMPLATE_PYTHON_EXTRA_PACKAGESrY   r   zpip install &FLEX_TEMPLATE_PYTHON_REQUIREMENTS_FILEz!pip install --no-cache-dir -U -r a  (pip check || (e=$?; echo "Building a container with incompatible dependencies is prevented by default. If you are sure you want to proceed, you need to create your own container image. See: https://cloud.google.com/dataflow/docs/guides/templates/configuring-flex-templates"; exit $e))FLEX_TEMPLATE_PYTHON_SETUP_FILEr   r   r   zRUN z && r   )
splitr]   r\   r   r   r   r   r   r   r   )r   r  r   r  r   package_listpackagepackages_pathpackage_argr   r   r  r  r  r  r  s                   r   BuildPythonImageDockerfilez$Templates.BuildPythonImageDockerfile  s   H S789: &' -3>?EEcJl	?KL|G:gY/|L58XXm5L12hh}-;-(	
 036sCDE
F 

23 oo:;<> oo )C/s<=>
? 

+, 28		1DE1DAKq!$1DDEyyHHH^$E'..u5L"//*=>EE66$&&++h// F 1 K M4 Fs   E:E?c                    d}dj                  |d         |d<   dj                  |      }dj                  |      }t        |j                               D cg c]  \  }}dj                  ||       }}}dj                  |      }	t	        j
                  |      j                  t        j                  |       |	|      }
|
S c c}}w )	a0  Builds Dockerfile contents for go flex template image.

    Args:
      flex_template_base_image: SDK version or base image to use.
      pipeline_paths: Path to pipeline binary.
      env: Dictionary of env variables to set in the container image.

    Returns:
      Dockerfile contents as string.
    z2
    FROM {base_image}

    {env}

    {copy}
    z/template/{}FLEX_TEMPLATE_GO_BINARYr   r   r   r   )r   r   r   )r   r]   r   r   r   r   r   r   )r   r  r   r  r  r  varvalr  r  r  s              r   BuildGoImageDockerfilez Templates.BuildGoImageDockerfile  s     &4%:%:%&&(C!"HH^$E'..u5L 6<CIIK5H5Hc3$5H 	  yyH"//*=>EE66$&	 F  s   Cc                     |dk(  rt         j                  | ||      S |dk(  rt         j                  | ||      S |dk(  rt         j                  | ||      S y)ax  Builds Dockerfile contents for flex template image.

    Args:
      flex_template_base_image: SDK version or base image to use.
      pipeline_paths: List of paths to pipelines and dependencies.
      env: Dictionary of env variables to set in the container image.
      sdk_language: SDK language of the flex template.

    Returns:
      Dockerfile contents as string.
    JAVAPYTHONGON)r   r  r  r  )r   r  r   sdk_languages       r   BuildDockerfilezTemplates.BuildDockerfile"  sx     v//0H0>E E		!112J2@#G G		--.F.<cC C 
r   c                     | D ]t  }|j                   st        dj                  |            |j                  st        dj                  |            |j                  r\t        dj                  |             y)zValidates ParameterMetadata objects in template metadata.

    Args:
      parameters: List of ParameterMetadata objects.

    Raises:
      ValueError: If is any of the required field is not set.
    zGInvalid template metadata. Parameter name field is empty. Parameter: {}zHInvalid template metadata. Parameter label field is empty. Parameter: {}zKInvalid template metadata. Parameter helpText field is empty. Parameter: {}N)name
ValueErrorr   labelhelpText)r   	parameters     r   _ValidateTemplateParametersz%Templates._ValidateTemplateParameters:  s}      	^^#VI.0 	0 __#VI.0 	0 #VI.0 	0  r   c                 |    |dk(  rd| vrt        d      |dk(  rd| vrt        d      |dk(  rd| vrt        d	      y
)a9  Builds and validates Flex template environment values.

    Args:
      env: Dictionary of env variables to set in the container image.
      sdk_language: SDK language of the flex template.

    Returns:
      True on valid env values.

    Raises:
      ValueError: If is any of parameter value is invalid.
    r  FLEX_TEMPLATE_JAVA_MAIN_CLASSzXFLEX_TEMPLATE_JAVA_MAIN_CLASS environment variable should be provided for all JAVA jobs.r  r
  zYFLEX_TEMPLATE_PYTHON_PY_FILE environment variable should be provided for all PYTHON jobs.r  r  zPFLEX_TEMPLATE_GO_BINARY environment variable should be provided for all GO jobs.T)r!  )r   r  s     r   __ValidateFlexTemplateEnvz#Templates.__ValidateFlexTemplateEnvR  su     v"A"L @ B B		!&DC&O B D D		";3"F > @ @r   c                    t        j                  t        j                  |       }t        j                         }|j                  st        dj                  |            |j                  |_        |j                  r|j                  |_        |j                  r0t        j                  |j                         |j                  |_        |j                  r|j                  |_
        |S )a   Builds and validates TemplateMetadata object.

    Args:
      template_metadata_json: Template metadata in json format.

    Returns:
      TemplateMetadata object on success.

    Raises:
      ValueError: If is any of the required field is not set.
    zEInvalid template metadata. Name field is empty. Template Metadata: {})r   JsonToMessager   TEMPLATE_METADATAr   r!  r   descriptionr   r%  yamlDefinition)template_metadata_jsontemplate_metadatatemplate_metadata_objs      r   _BuildTemplateMetadataz Templates._BuildTemplateMetadatak  s     !..y/J/J/EG%779!! 0067H0IK K!2!7!7$$*;*G*G'##++,=,H,HI):)E)E&''->-M-M*  r   c                    | j                   r| j                   S | j                  r| j                  S | j                  r 	 t        j	                  | j                        S t        j	                  t              S # t
        j                  $ r Y .w xY w)+Returns the image path for a YAML template.)r%   
yaml_imager   r   _ExtractYamlTemplateImager   r8   r4   )argss    r   GetYamlTemplateImagezTemplates.GetYamlTemplateImage  s{     zzZZ	__ 2243E3EFF ../JKK %% s   A6 6BBc                 f   t         j                  j                  |       }t        j                         }t
        j                  j                  |      }	 t        j                  |j                  |            }|d   S # t        $ r*}t        j                  dj                  |            |d}~ww xY w)r3  zSUnable to read file {0} due to incorrect file path or insufficient read permissionsNr%   )r   YAML_TEMPLATE_GCS_LOCATIONr   r	   StorageClientr
   ObjectReferenceFromUrljsonload
ReadObject	Exceptionr   r8   )r;   yaml_gcl_template_pathstorage_clientobj_refgeneric_template_definitiones         r   r5  z#Templates._ExtractYamlTemplateImage  s     'AAHH !..0N**223IJG$(II

#
#G
,%! 'w//  $$$f%;< s   $A= =	B0%B++B0c                    | dk(  rt         j                  S | dk(  rt         j                  S | dk(  rt         j                  S | dk(  rt         j                  S | dk(  rt         j
                  S | dk(  rt         j                  S | dk(  r%t        j                  d       t         j                  S | d	k(  rt         j                  S | d
k(  rt         j                  S | dk(  rt         j                  S | S )a  Returns latest base image for given sdk version.

    Args:
        flex_template_base_image: SDK version or base image to use.

    Returns:
      If a custom base image value is given, returns the same value. Else,
      returns the latest base image for the given sdk version.
    JAVA11JAVA17JAVA21JAVA11_DISTROLESSJAVA17_DISTROLESSJAVA21_DISTROLESSJAVA8z]JAVA8 is deprecated and redirected to JAVA11. This option will be removed in a future releasePYTHON3r  GO_DISTROLESS)r   FLEX_TEMPLATE_JAVA11_BASE_IMAGEFLEX_TEMPLATE_JAVA17_BASE_IMAGEFLEX_TEMPLATE_JAVA21_BASE_IMAGE*FLEX_TEMPLATE_JAVA11_DISTROLESS_BASE_IMAGE*FLEX_TEMPLATE_JAVA17_DISTROLESS_BASE_IMAGE*FLEX_TEMPLATE_JAVA21_DISTROLESS_BASE_IMAGEr   warning FLEX_TEMPLATE_PYTHON3_BASE_IMAGEFLEX_TEMPLATE_GO_BASE_IMAGE&FLEX_TEMPLATE_GO_DISTROLESS_BASE_IMAGE)r   s    r   r   z#Templates._GetFlexTemplateBaseImage  s      8+666	!X	-666	!X	-666	!%8	8AAA	!%8	8AAA	!%8	8AAA	!W	,	kk0 666	!Y	.777	!T	)222	!_	4===##r   c                    | dk(  r.t         j                  t         j                  j                        S | dk(  r.t         j                  t         j                  j                        S | dk(  r.t         j                  t         j                  j
                        S | dk(  r.t         j                  t         j                  j                        S y)zBuilds SDKInfo object.

    Args:
      sdk_language: SDK language of the flex template.

    Returns:
      SDKInfo object
    r  )languager  YAMLr  N)r   SDK_INFOSDK_LANGUAGEr  r  r\  r  )r  s    r   _BuildSDKInfozTemplates._BuildSDKInfo  s     v)?)?)D)DEE		!)?)?)F)FGG		)?)?)D)DEE		)?)?)B)BCC 
r   c                 P   t        j                         5 }t        j                  j	                  |d      }t        j
                  ||d       t        j                         }t        j                  j                  |       }|j                  ||      cddd       S # 1 sw Y   yxY w)a>  Stores flex template container spec file in GCS.

    Args:
      template_file_gcs_location: GCS location to store the template file.
      container_spec_json: Container spec in json format.

    Returns:
      Returns the stored flex template file gcs object on success.
      Propagates the error on failures.
    ztemplate-file.jsonr   )newlineN)r   TemporaryDirectoryospathr]   WriteFileContentsr	   r:  r
   r;  r<  CopyFileToGCS)template_file_gcs_locationcontainer_spec_jsontemp_dir
local_pathrB  rC  s         r   _StoreFlexTemplateFilez Templates._StoreFlexTemplateFile  s{     
	!	!	#x77<<*>?jj*=tL"002n,,445OPg))*g> 
$	#	#s   A=BB%c	                    d}	|rt         j                  |      }	t         j                  |      }
d}|rBt         j                  |j                  t         j
                        }t         j                  j                  }|j                  r|nd}|j                  rdnd}t         j                  |j                  |j                  |j                  |j                  |j                  |j                   |j"                  r|j"                  n|j$                  |j$                  |j&                  ||j(                  |j*                  ||j,                  r|j,                  ng |rt         j                  |      nd      }t         j/                  ||	|
||||      }t1        j2                  |      }t5        j6                  t5        j8                  |      ddd      }|r|S 	 t         j;                  | |       t<        j>                  jA                  d	jC                  | |             y# tD        jF                  $ r}tI        jJ                  |      d}~ww xY w)
a  Builds container spec and stores it in the flex template file in GCS.

    Args:
      template_file_gcs_location: GCS location to store the template file.
      image: Path to the container image.
      template_metadata_json: Template metadata in json format.
      sdk_language: SDK language of the flex template.
      print_only: Only prints the container spec and skips write to GCS.
      template_args: Default runtime parameters specified by template authors.
      image_repository_username_secret_id: Secret manager secret id for username
        to authenticate to private registry.
      image_repository_password_secret_id: Secret manager secret id for password
        to authenticate to private registry.
      image_repository_cert_path: The full URL to self-signed certificate of
        private registry in Cloud Storage.

    Returns:
      Container spec json if print_only is set. A success message with template
      file GCS path and container spec otherewise.
    NTrE   )r   r   r   r   r   r   r   stagingLocationr   r   r   r   r   r   r   )r%   metadatasdkInfodefaultEnvironmentimageRepositoryUsernameSecretIdimageRepositoryPasswordSecretIdimageRepositoryCertPath   )rY   z: )	sort_keysindent
separatorszkSuccessfully saved container spec in flex template file.
Template File GCS Location: {}
Container Spec:

{})&r   r1  r_  r   r   FLEX_TEMPLATE_USER_LABELS_VALUEIP_CONFIGURATION_ENUM_VALUEr   r   r   FLEX_TEMPLATE_ENVIRONMENTr   r   r   r   r   r   r   r   r   r   r   r   CONTAINER_SPECr   MessageToJsonr=  dumpsloadsrk  r   statusPrintr   r6   r7   r   r8   )rg  r%   r.  r  
print_onlyr   #image_repository_username_secret_id#image_repository_password_secret_idimage_repository_cert_pathr/  sdk_infodefault_environmentr   r   r   r   container_specrh  container_spec_pretty_jsonr=   s                       r   BuildAndStoreFlexTemplateFilez'Templates.BuildAndStoreFlexTemplateFile  s>   < #::
 "&&|4H"99

.
.

3
35 88JJj%88*d   77$T  &??+AA".."..''"--#77(( %22.;.L.L'88"//*$22".. 7!.!E!E "/!E!EKM   )HH#3  I  5#'' @ )( --".(K(K : . <N #00@!%

&'	" 
 ''	,&&'A'AC	jj v02LM	O
 (( ,$$U++,s   AH I1IIc                     t        j                  |       j                  t        j                  z  |z  }t        j
                  | |       y)zAdds the given permissions to a file or directory.

    Args:
      path: The path to the file or directory.
      permissions: The permissions to add.

    Raises:
      OSError: If the chmod fails.
    N)rc  statst_moder   ALL_PERMISSIONS_MASKchmod)rd  permissionss     r   _AddPermissionszTemplates._AddPermissions[  s:     		 > >>K HHT;r   c                    t        j                  |       D ]s  \  }}}t        j                  |t        j                         |D ]D  }t        j                  t         j
                  j                  ||      t        j                         F u y)zWalks a dir to chmod itself and its contents with the configured access.

    Args:
      top_dir_path: The path to the top-level directory.

    Raises:
      OSError: If the chmod fails.
    N)rc  walkr   r  DIR_PERMISSIONS_MASKrd  r]   FILE_PERMISSIONS_MASK)top_dir_pathdirpath_	filenamesfilenames        r   _ChmodRWorldReadablezTemplates._ChmodRWorldReadablek  sf     "$!6I)G)GH(!!GGLL(+Y-L-L	
   "7r   c	                 r   t         j                  ||       t        j                         5 }	t        j
                  j                  dj                  |	             g }
|}|r|}n|r|g}|D ]  }t        j                  j                  |      }t        j                  j                  |      r<t        j                  ||	      }	 t         j                  |t         j                         ngt        j$                  |t        j                  j'                  |	t        j                  j)                  |                  }	 t         j+                  |       |
j-                  t        j                  j/                  |      d           t        j
                  j                  d       t         j1                  ||
||      }t        j                  j'                  |	d      }t        j2                  ||       t        j
                  j                  dj                  |             t5        j6                         }t9        j:                  d!i d| d	d
d|dddddddd
d|	ddddd|ddddddddddddddd|r|nddd}t        j
                  j                  d        t9        j<                  |d
|       	 ddd       y# t         $ r( t	        j"                  dj                  |             Y w xY w# t         $ r( t	        j"                  dj                  |             Y w xY w# 1 sw Y   yxY w)"ah  Builds the flex template docker container image and stores it in GCR.

    Args:
      image_gcr_path: GCR location to store the flex template container image.
      flex_template_base_image: SDK version or base image to use.
      jar_paths: List of jar paths to pipelines and dependencies.
      py_paths: List of python paths to pipelines and dependencies.
      go_binary_path: Path to compiled Go pipeline binary.
      env: Dictionary of env variables to set in the container image.
      sdk_language: SDK language of the flex template.
      gcs_log_dir: Path to Google Cloud Storage directory to store build logs.
      cloud_build_service_account: Service account to be used by Cloud
        Build to build the image.

    Returns:
      True if container is built and store successfully.

    Raises:
      ValueError: If the parameters values are invalid.
    z$Copying files to a temp directory {}z/Could not adjust permissions for copied file {}z4Could not adjust permissions for copied directory {}   zCGenerating dockerfile to build the flex template container image...
Dockerfilez"Generated Dockerfile. Contents: {}tagno_cacheFmessagessubstitutionsN
arg_configzcloudbuild.yamlis_specified_sourceT	no_sourcesourcegcs_source_staging_dirignore_filearg_gcs_log_dirarg_machine_typearg_disk_sizearg_worker_poolarg_dirarg_revisionarg_git_source_dirarg_git_source_revisionarg_service_account	buildpackz/Pushing flex template container image to GCR...r   )r   #_Templates__ValidateFlexTemplateEnvr   rb  r   r  r  r   rc  rd  abspathisfileshutilcopy2r  r  OSErrorrV  copytreer]   basenamer  r\   r  r  re  r   r   r   CreateBuildConfigBuild)image_gcr_pathr   	jar_pathspy_pathsgo_binary_pathr   r  gcs_log_dircloud_build_service_accountri  pipeline_filesr  rd  	absl_path	copy_filecopy_dirr  dockerfile_pathr  build_configs                       r   BuildAndStoreFlexTemplateImagez(Templates.BuildAndStoreFlexTemplateImage|  s$   @ ''\:		!	!	#x	jj=DDXNOne	 $GGOOD)	77>>)$ll9h7)	%%9:: __ggll8RWW%5%5i%@A(
**84 	bggmmI6q9:; > 
jj
OQ%556N6Dc6BD X|<oo/BC	jj
.
5
56I
JL !224h 22   	
 ' #   "&  &       !" "#$ #'%* - *-0 1l4 
jjHI%6e 
$	#&  KKAHH  KKFMMC 
$	#sV   BL-$K'AL-:K9E-L--K62L-5K66L-9-L*&L-)L**L--L6c                    t         j                  | j                  t         j                        }t         j                  | j                  t         j
                        }d}d}| j                  r$| j                  }|rt         j                  |      }t         j                  | j                  t         j                        }| j                  xs t        }t         j                  j                  }| j                  r|nd}d}	| j                  rS| j                  dk(  rt         j                  j                   }	n)| j                  dk(  rt         j                  j"                  }	t         j%                  t         j'                  | j(                  | j*                  t         j-                  | j.                  | j0                  | j2                  | j4                  | j6                  | j8                  | j:                  | j<                  r| j<                  n| j>                  | j>                  | j@                  || jB                  | jD                  | jF                  |	| jH                  r| jH                  ng |rt         j                  |      nd| jJ                  r| jJ                  ng       |||rt         j                  |      nd            }
tM               jO                  | jP                  xs
 tS               ||
      }	 t         jU                         jW                  |      S # tX        jZ                  $ r}t]        j^                  |      d}~ww xY w)	zCalls the create job from flex template APIs.

    Args:
      template_args: Arguments for create template.

    Returns:
      (Job)
    NrE   SPEED_OPTIMIZEDCOST_OPTIMIZED)r   r   r   r   r   r   launcherMachineTyper   rm  r   r   r   r   r   
flexrsGoalr   r   r   )r   containerSpecGcsPathrj   r   transformNameMappingsr   )launchParameter)r2   r1   launchFlexTemplateRequest)0r   r   r   FLEX_TEMPLATE_PARAMETERS_VALUEr   *FLEX_TEMPLATE_TRANSFORM_NAME_MAPPING_VALUEr   r   rx  r;   r4   ry  r   r   r   FLEXRS_GOAL_ENUM_VALUEFLEXRS_SPEED_OPTIMIZEDFLEXRS_COST_OPTIMIZEDLAUNCH_FLEX_TEMPLATE_REQUESTFLEX_TEMPLATE_PARAMETERr   r   rz  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   3DataflowProjectsLocationsFlexTemplatesLaunchRequestr:   r#   r   r   r6   r7   r   r8   )r   r   r   r   r   r   r;   r   r   r   r   r<   r=   s                r   CreateJobFromFlexTemplatez#Templates.CreateJobFromFlexTemplate  s    22  )"J"JLK&==--<<> %%&77	@@%; A  	 !77,,113
 ''F+FI66HHJ%2%E%Ez4K  		"	"&7	766MM$$(8866LL11!99!**!.!;!;!;;$1$G$G(44(44%--(33)==$1$G$G<I=]88$1$B$B - > >(55 0*88(44&3&K&K&<I++=,M8813 & &/%N%N)9 &O &+/ %@@ "==5 < 8 $"45@ !??%0 @ 2FJE : "L 2 #MDH   99**:jl"& : ( 
,--/66w??(( ,$$U++,s   3"L M)L>>Mr   )NNNN)Trx   ry   rz   r{   r   CreateJobFromTemplateRequestr   LaunchTemplateParametersr   ParametersValuer   LaunchFlexTemplateRequestr  r   FlexTemplateRuntimeEnvironmentrz  r   rx  TransformNameMappingValuer   LaunchFlexTemplateParameterr  r  TransformNameMappingsValuer  r   ry  FlexrsGoalValueValuesEnumr  TemplateMetadatar+  SDKInfor]  LanguageValueValuesEnumr^  ContainerSpecr{  r'   rP  rQ  rR  rS  rT  rU  rW  rX  rY  r9  r  S_IRWXUS_IRWXGS_IRWXOr  S_IWUSRS_IRUSRS_IRGRPS_IROTHr  S_IXGRPS_IXOTHr  r   r-   r   r   r   r   r  r  r  r  r%  r  r1  r7  r5  r   r_  rk  r  r  r  r  r  r   r   r   r   r     s   4$&CC.02KK%?%O%O"!2!4!N!N#33/1PP99 " !:: 0 ./KK#:#J#J 88 - !2 !""#A#A , ""#<#< '):: ((("$,,DD,$&44.$5h$?!$5h$?!$5h$?!/@4/P,/@4/P,/@4/P,%6y%A" 1$ 7+<T4+H(<  llT\\!DLL0  llT\\!DLL04<<? 
 llT\\!DLL04<<?$,,N  < < @ @ F, F,P P, P,d  " ! !F E EV $ $L C C. 0 0.  0 ! !B L L  0 0$ "$ "$H D D$ ? ?&  37HLHL?C[, [,z     
 
  r rh W, W,r   r   c                   b    e Zd ZdZ e       j
                  Zed        Ze	 	 	 	 	 	 	 dd       Z	y)Messagesz+The Messages set of Dataflow API functions.c                  *    t               j                  S r   )r    projects_locations_jobs_messagesr   r   r   r-   zMessages.GetServiceR  r   r   Nc           
         |xs
 t               }|xs t        }t               j                  | |||||||      }	 t        j                         j                  |      S # t        j                  $ r}	t        j                  |	      d}	~	ww xY w)a  Calls the Dataflow Metrics.Get method.

    Args:
      job_id: The job to get messages about.
      project_id: The project which owns the job.
      region_id: The regional endpoint of the job.
      minimum_importance: Filter to only get messages with importance >= level
      start_time: If specified, return only messages with timestamps >=
        start_time. The default is the job creation time (i.e. beginning of
        messages).
      end_time: Return only messages with timestamps < end_time. The default is
        now (i.e. return up to the latest messages available).
      page_size: If specified, determines the maximum number of messages to
        return.  If unspecified, the service may choose an appropriate default,
        or may return an arbitrarily large number of results.
      page_token: If supplied, this should be the value of next_page_token
        returned by an earlier call. This will cause the next page of results to
        be returned.

    Returns:
      (ListJobMessagesResponse)
    )r0   r1   r2   r   endTimeminimumImportancepageSize	pageTokenN)r#   r4   r   0DataflowProjectsLocationsJobsMessagesListRequestr  r-   Listr6   r7   r   r8   )
r9   r:   r;   minimum_importancer   end_time	page_size
page_tokenr<   r=   s
             r   r  zMessages.ListV  s    > +z|J88I 66, 7  ,  "''00(( ,$$U++,s   "A B1BB)NNNNNNN)
rx   ry   rz   r{   r   r  r~   r   r-   r  r   r   r   r  r  L  sW    3" 44  @ @ "., .,r   r  c                   V    e Zd ZdZed        Zedd       Zedd       Zedd       Zy)	SnapshotszCloud Dataflow snapshots api.c                  *    t               j                  S r   )r   projects_locations_snapshotsr   r   r   r-   zSnapshots.GetService  r   r   Nc                    |xs
 t               }|xs t        }t               j                  | ||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)a  Calls the Dataflow Snapshots.Delete method.

    Args:
      snapshot_id: The id of the snapshot to delete.
      project_id: The project that owns the snapshot.
      region_id: The regional endpoint of the snapshot.

    Returns:
      (DeleteSnapshotResponse)
    
snapshotIdr1   r2   N)r#   r4   r   /DataflowProjectsLocationsSnapshotsDeleteRequestr  r-   Deleter6   r7   r   r8   snapshot_idr:   r;   r<   r=   s        r   r  zSnapshots.Delete  s     +z|J88I 55j 6 J ,!!#**733(( ,$$U++,   "A B,BBc                    |xs
 t               }|xs t        }t               j                  | ||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)a  Calls the Dataflow Snapshots.Get method.

    Args:
      snapshot_id: The id of the snapshot to get.
      project_id: The project that owns the snapshot.
      region_id: The regional endpoint of the snapshot.

    Returns:
      (GetSnapshotResponse)
    r  N)r#   r4   r   ,DataflowProjectsLocationsSnapshotsGetRequestr  r-   r"   r6   r7   r   r8   r	  s        r   r"   zSnapshots.Get  s     +z|J88I!NNj O JG,!!#''00(( ,$$U++,r  c                    |xs
 t               }|xs t        }t               j                  | ||      }	 t        j                         j                  |      S # t        j                  $ r}t        j                  |      d}~ww xY w)a0  Calls the Dataflow Snapshots.List method.

    Args:
      job_id: If specified, only snapshots associated with the job will be
        returned.
      project_id: The project that owns the snapshot.
      region_id: The regional endpoint of the snapshot.

    Returns:
      (ListSnapshotsResponse)
    )r0   r1   r2   N)r#   r4   r   -DataflowProjectsLocationsSnapshotsListRequestr  r-   r  r6   r7   r   r8   )r9   r:   r;   r<   r=   s        r   r  zSnapshots.List  s     +z|J88I!OOyJ P @G,!!#((11(( ,$$U++,r  rv   )	rx   ry   rz   r{   r   r-   r  r"   r  r   r   r   r  r    sS    %< < , ,, , ,* , ,r   r  )F)*r{   
__future__r   r   r   r=  rc  r  r  r   apitools.base.pyr   r   r6   !googlecloudsdk.api_lib.cloudbuildr   googlecloudsdk.api_lib.storager	   r
   googlecloudsdk.api_lib.utilr   !googlecloudsdk.command_lib.buildsr   googlecloudsdk.corer   r   googlecloudsdk.core.utilr   r   r   r   r4   r   r   r#   r'   r)   r   r   r   r  r  r   r   r   <module>r     s    ; &  '  	    % > = 6 7 , 2 9 # * * 
  + II;\`, `,F$, $,NR# R#jg, g,T9, 9,xI, I,r   