
    9&                         d 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Z	 ddZd Z	 ddZd Z	 	 	 	 	 	 	 	 	 ddZd Zy)z/Utilities for AI Platform custom jobs commands.    )absolute_import)division)unicode_literals)
local_util)build)utils)	arg_utils)log)filesz(aiplatform.projects.locations.customJobsNc                     | j                  d             }| j                  d      } ||j                  d            }|j                  d      }|rEt        j                  ||j                        |_        t        |j                  dd            |_        ||_        t        |j                  dd            |_	        |j                  d	      }|j                  d
      }|j                  d      }	|r!| j                  d      }
 |
|      |_
        |S |s|s|	r%| j                  d      } |||xs g |	      |_        |S )a  Constructs the specification of a single worker pool.

  Args:
    aiplatform_client: The AI Platform API client used.
    spec: A dict whose fields represent a worker pool config.
    python_package_uri: str, The common python package uris that will be used by
      executor image, supposedly derived from the gcloud command flags.

  Returns:
    A WorkerPoolSpec message instance for setting a worker pool in a custom job.
  WorkerPoolSpecMachineSpeczmachine-type)machineTypezaccelerator-typezaccelerator-count   zreplica-countcontainer-image-uriexecutor-image-uripython-moduleContainerSpec)imageUriPythonPackageSpec)executorImageUripackageUrispythonModule)
GetMessagegetr	   ChoiceToEnumAcceleratorTypeValueValuesEnumacceleratorTypeintacceleratorCountmachineSpecreplicaCountcontainerSpecpythonPackageSpec)aiplatform_clientspecpython_package_uriworker_pool_specmachine_spec_msgmachine_specaccelerator_typecontainer_image_uriexecutor_image_uripython_modulecontainer_spec_msgpython_package_spec_msgs               Alib/googlecloudsdk/command_lib/ai/custom_jobs/custom_jobs_util.py_ConstructSingleWorkerPoolSpecr2       sJ    D&112BCE&11-@!dhh~.FG,XX01#,#9#9*II$KL $'1Da(H$IL!!-"%dhh&B"C!67xx 45((?+-*55oF%7$&&" 
 /=/::;NO)@+'-2"*$&
 
    c                     g }|D ]F  }|r|j                  t        | |fi |       "|j                   | j                  d                    H |S )a  Constructs the specification of the worker pools in a CustomJobSpec instance.

  Args:
    aiplatform_client: The AI Platform API client used.
    specs: A list of dict of worker pool specifications, supposedly derived from
      the gcloud command flags.
    **kwargs: The keyword args to pass down to construct each worker pool spec.

  Returns:
    A list of WorkerPoolSpec message instances for creating a custom job.
  r   )appendr2   r   )r%   specskwargsworker_pool_specsr&   s        r1   _ConstructWorkerPoolSpecsr9   L   sa     d
():D
KF
KM M0;;<LMOP  
r3   c           	      h   |xs t        j                  || d      }t        j                  d|t	        j
                  |      |||d| t        j                  j                  d       dd|g}	t        j                  |	       t        j                  j                  dj                  |             |S )	zOBuild a training image from local package and push it to Cloud for later usage.T)	base_nameprojectis_gcr)
base_imagehost_workdirmain_scriptr.   output_image_namez,
A custom container image is built locally.
dockerpushz=
Custom container image [{}] is created for your custom job.
 )docker_utilsGenerateImageNamedocker_build
BuildImager   ExpandHomeDirr
   statusPrintExecuteDockerCommandformat)
r<   job_namer>   local_packagescriptrA   r.   r7   output_imagepush_commands
             r1   _PrepareTrainingImagerS   d   s     # 8l&D&D'$'8,  &&}5!$ 	 **CDFL1,##L1**GNN
 
r3   c              #     K   d}| rd| d   v r| d   j                  d      }| d   j                  d      }| d   j                  dd      }|rt        j                  |      }n| d   j                  d      }| d   j                  dd      }t        |||||||| d   j                  dd      | d   j                  d	d      | d   j                  d
d      
      }| D ]$  }	|r|	r|	j	                         }
||
d<   |
 !|	 & yw)a  Update the given worker pool specifications if any contains local packages.

  If any given worker pool spec is specified a local package, this builds
  a Docker image from the local package and update the spec to use it.

  Args:
    worker_pool_specs: list of dict representing the arg value specified via the
      `--worker-pool-spec` flag.
    job_name: str, the display name of the custom job corresponding to the
      worker pool specs.
    project: str, id of the project to which the custom job is submitted.

  Yields:
    All updated worker pool specifications that uses the already built
    packages and are expectedly passed to a custom-jobs create RPC request.
  Nzlocal-package-pathr   r   r   rP   zoutput-image-urirequirementszextra-packagesz
extra-dirs)
r<   rN   r>   rO   rP   rA   r.   rU   extra_packages
extra_dirsr   )popr   ModuleToPathrS   copy)r8   rN   r<   image_built_for_first_workerr>   rO   r.   rP   rQ   r&   new_specs              r1   +UpdateWorkerPoolSpecsIfLocalPackageRequiredr]      s4    & "&/3DQ3GG"1%))*>?J%a(,,-ABM%a(,,_dCM&&}5f #''1f$Q'++,>EL#8#&#&q)--ndC(+//0@$G$Q'++L$?
$A   d#h(Dh$%nj  s   DDc
                    |}|||_         |||_        |r||_        |r||_        |rt	        | |fi |
|_        |rL|j
                  D ]=  }|j                  r||j                  _        |j                  s-||j                  _        ? |r/|j
                  D ]   }|j                  s||j                  _	        " |	r|	|_
        |S )a  Constructs the spec of a custom job to be used in job creation request.

  Args:
    aiplatform_client: The AI Platform API client used.
    base_config: A base CustomJobSpec message instance, e.g. imported from a
      YAML config file, as a template to be overridden.
    network: user network to which the job should be peered with (overrides yaml
      file)
    service_account: A service account (email address string) to use for the
      job.
    enable_web_access: Whether to enable the interactive shell for the job.
    enable_dashboard_access: Whether to enable the access to the dashboard built
      on the job.
    worker_pool_specs: A dict of worker pool specification, usually derived from
      the gcloud command argument values.
    args: A list of arguments to be passed to containers or python packge,
      supposedly derived from the gcloud command flags.
    command: A list of commands to be passed to containers, supposedly derived
      from the gcloud command flags.
    persistent_resource_id: The name of the persistent resource from the same
      project and region on which to run this custom job.
    **kwargs: The keyword args to pass to construct the worker pool specs.

  Returns:
    A CustomJobSpec message instance for creating a custom job.
  )networkserviceAccountenableWebAccessenableDashboardAccessr9   workerPoolSpecsr#   argsr$   commandpersistentResourceId)r%   base_configr_   service_accountenable_web_accessenable_dashboard_accessr8   rd   re   persistent_resource_idr7   job_specr(   s                r1   ConstructCustomJobSpecrm      s    L (H -H0H%<H"8, 806 8H	$44		'	'.2&&+		+	+26**/	 5
 $44		'	'18&&. 5 $:H!	/r3   c                 B    | |v xr t        |j                  |             S N)boolr   )keyr7   s     r1   _IsKwargsDefinedrr      s    		04

300r3   ro   )	NNNNNNNNN)__doc__
__future__r   r   r   )googlecloudsdk.command_lib.ai.custom_jobsr   $googlecloudsdk.command_lib.ai.dockerr   rG   r   rE   $googlecloudsdk.command_lib.util.apisr	   googlecloudsdk.corer
   googlecloudsdk.core.utilr   CUSTOM_JOB_COLLECTIONr2   r9   rS   r]   rm   rr   rD   r3   r1   <module>r{      sw    6 &  ' @ F F : # * C 
 7;)X< )-<1l  	CL1r3   