
    8                         d Z ddlmZ ddlmZ ddlm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 Zd Zd Zd Zd Zd Z	 ddZd Zd Zd Zd Zd Z d Z!d Z"d Z#y)z:Validations of the arguments of custom-jobs command group.    )absolute_import)division)unicode_literalsN)util)
exceptions)	constants)
validation)
local_util)utils)filesc                 N    t        j                  | t        j                         y)zIValidate whether the given region is allowed for specifically custom job.)available_regionsN)r	   ValidateRegionr   SUPPORTED_TRAINING_REGIONS)regions    ;lib/googlecloudsdk/command_lib/ai/custom_jobs/validation.pyr   r       s    	 D DF    c                 `    | j                   rt        | j                   |       yt        |       y)z;Validate the argument values specified in `create` command.N)worker_pool_spec_ValidateWorkerPoolSpecArgs"_ValidateWorkerPoolSpecsFromConfig)argsjob_spec_from_configversions      r   ValidateCreateArgsr   &   s&     
 5 5w?&';<r   c                 h    | d   st        j                  dd      t        | |       t        |        y)a  Validates the argument values specified via `--worker-pool-spec` flags.

  Args:
    worker_pool_specs: List[dict], a list of worker pool specs specified in
      command line.
    version: str, the API version this command will interact with, either GA or
      BETA.
  r   --worker-pool-speczCEmpty value is not allowed for the first `--worker-pool-spec` flag.N)r   InvalidArgumentException%_ValidateHardwareInWorkerPoolSpecArgs%_ValidateSoftwareInWorkerPoolSpecArgs)worker_pool_specsr   s     r   r   r   /   s=     
1	

-
-MO O ((97C'(9:r   c                    | D ]  }|sd|vrt        j                  dd      d|v rd|vrt        j                  dd      |j                  dd      }|sSt        j                  d|      j
                  }|j                         D cg c]&  }|j                  d	      s|j                  d
      r|( }}||vst        j                  ddj                  |dj                  d t        |      D                           yc c}w )a  Validates the hardware related fields specified in `--worker-pool-spec` flags.

  Args:
    worker_pool_specs: List[dict], a list of worker pool specs specified in
      command line.
    api_version: str, the API version this command will interact with, either GA
      or BETA.
  zmachine-typer   z9Key [machine-type] required in dict arg but not provided.zaccelerator-countzaccelerator-typezDKey [accelerator-type] required as [accelerator-count] is specified.NMachineSpecNVIDIATPUzWFound invalid value of [accelerator-type]: {actual}. Available values are [{expected}]., c              3       K   | ]  }|  y w)N ).0vs     r   	<genexpr>z8_ValidateHardwareInWorkerPoolSpecArgs.<locals>.<genexpr>e   s     %E1DAa1Ds   )actualexpected)r   r   getapi_util
GetMessageAcceleratorTypeValueValuesEnumnames
startswithformatjoinsorted)r!   api_versionspecaccelerator_type	type_enumtypevalid_typess          r   r   r   A   s*     d	t	#11 GI 	I 
	$);4)G11 R
 	

 "4d;	'';((F(F 	 '__.
.Tx(DOOE,B . 	 
 ;.33"45;V* II%E1D%EE 6< 6GH H-  "
s   +Dc                 \    t        | d         }t        |       dkD  rt        | dd |       yy)zJValidates the software fields specified in all `--worker-pool-spec` flags.r      N)&_ValidateSoftwareInFirstWorkerPoolSpeclen&_ValidateSoftwareInRestWorkerPoolSpecs)r!   has_local_packages     r   r    r    h   s?    < 		a*+<QR+@+<>  r   c                 :    d| v rt        |        yt        |        y)zValidates the software related fields specified in the first `--worker-pool-spec` flags.

  Args:
    spec: dict, the specification of the first worker pool.

  Returns:
    A boolean value whether a local package will be used.
  local-package-pathTF)+_ValidateWorkerPoolSoftwareWithLocalPackage/_ValidateWorkerPoolSoftwareWithoutLocalPackages)r8   s    r   r?   r?   r   s"     T!/53D9r   c                     | D ][  }|s|r/h d}t        |j                  |j                               d       7d|v rt        j                  dd      t        |       ] y)a2  Validates the argument values specified in all but the first `--worker-pool-spec` flags.

  Args:
    specs: List[dict], the list all but the first worker pool specs specified in
      command line.
    is_local_package_specified: bool, whether local package is specified
      in the first worker pool.
  >   scriptrequirements
extra-dirspython-moduleextra-packagesexecutor-image-uricontainer-image-urizA local package has been specified in the first `--worker-pool-spec` flag and to be used for all workers, do not specify these keys elsewhere.unexpected_keysreasonrD   r   zPKey [local-package-path] is only allowed in the first `--worker-pool-spec` flag.N)_RaiseErrorIfUnexpectedKeysintersectionkeysr   r   rF   )specsis_local_package_specifiedr8   software_fieldss       r   rA   rA      sm     d	#
 	$+88E;	=  4'33",. . 	8=1 r   c                    d| v sJ t        | d   d       d| vrt        j                  dd      d| v d| v z   dk7  rt        j                  dd	      d
| v r_| d
   }|j                  d      d   }g d}||vr'|j	                  d      st        j                  dd      	 t        j                  |       yy# t        $ r+}t        j                  ddj                  ||            d}~ww xY w)z^Validate the software in a single `--worker-pool-spec` when `local-package-path` is specified.rD   r   )	flag_namerM   zLKey [executor-image-uri] is required when `local-package-path` is specified.rK   rH   r>   z_Exactly one of keys [python-module, script] is required when `local-package-path` is specified.output-image-uri/r   )zgcr.ioz	eu.gcr.iozasia.gcr.ioz	us.gcr.ioz-docker.pkg.devzSThe value of `output-image-uri` has to be a valid gcr.io or Artifact Registry image+'{}' is not a valid container image uri: {}N)	_RaiseErrorIfNotExistsr   r   splitendswithdocker_utilsValidateRepositoryAndTag
ValueErrorr4   )r8   output_imagehostnamecontainer_registrieses        r   rE   rE      s1   		%%	%
 ,@B %

-
-V 
 (d"23q8

-
-	23 3
 4*+L!!#&q)HN++H4E4E5//

_  ++L9     //

8
?
?A    s    B7 7	C+ &C&&C+c                 ,   d| vsJ d| v }d| v }d| v }||z   dk7  rt        j                  dd      |r|rt        j                  dd      |r|st        j                  dd	      h d
}|j                  | j                               }t	        |d       y)zbValidate the software in a single `--worker-pool-spec` when `local-package-path` is not specified.rD   rM   rN   rK   r>   r   zJExactly one of keys [executor-image-uri, container-image-uri] is required.zKKey [python-module] is not allowed together with key [container-image-uri].z Key [python-module] is required.>   rH   rI   rJ   rL   z_Only allow to specify together with `local-package-path` in the first `--worker-pool-spec` flag)rQ   N)r   r   rS   rT   rR   )r8   has_executor_imagehas_container_imagehas_python_modulelocal_package_only_keysrP   s         r   rF   rF      s     
T	))	)+t3-5%-..14

-
-
 
 .

-
-
"$ $
  1

-
-@B B ,88E/nr   c           
          | r?t        j                  ddj                  dj                  t	        |             |            y )Nr   z(Keys [{keys}] are not allowed: {reason}.r&   )rT   rQ   )r   r   r4   r5   r6   rO   s     r   rR   rR      sJ    

-
-HOO6/23F P DE E r   c                 $   | j                   D ]  }|j                  xr. |j                  j                  xs |j                  j                  }|j                  xr |j                  j
                  }|r|s|rj|rmt        j                  dd       y)zHValidate WorkerPoolSpec message instances imported from the config file.z--configzuExactly one of fields [pythonPackageSpec, containerSpec] is required for a [workerPoolSpecs] in the YAML config file.N)workerPoolSpecspythonPackageSpecexecutorImageUripythonModulecontainerSpecimageUrir   r   )job_specr8   use_python_packageuse_containers       r   r   r      s     &&d// -// 	,++  &&F4+=+=+F+FM,m6H//
JL L 'r   c                 f   g }| j                   r|j                  d       | j                  r|j                  d       | j                  r|j                  d       | j                  r|j                  d       | j
                  r|j                  d       | j                  r|j                  d       |S )zAReturns names of all the flags specified only for image building.rH   rK   rI   rL   rJ   rZ   )rH   appendpython_modulerI   extra_packages
extra_dirsoutput_image_uri)r   image_build_argss     r   _ImageBuildArgSpecifiedr~     s    	[[H%	O,	N+	,-	__L)	./	r   c           
         t        |       }|sy| j                  sK| j                  s?t        j                  ddgdj                  dj                  t        |                        | j                  rd}n&t        j                  | j                        | _        d}t        j                  j                  t        j                  j                  | j                  | j                              }t        j                  j                  |      rt        j                  j                  |      s:t        j                   |dj                  | j                  | j                              | j"                  xs g D ]  }t        j                  j                  t        j                  j                  | j                  |            }t        j                  j                  |      r t        j                  j                  |      rt        j                   ddj                  || j                               | j$                  xs g D ]  }t        j                  j                  t        j                  j                  | j                  |            }t        j                  j                  |      r t        j                  j'                  |      rt        j                   d	d
j                  || j                               | j(                  r#| j(                  }	 t+        j,                  |       yt+        j0                  | j                        | _        y# t.        $ r+}	t        j                   ddj                  ||	            d}	~	ww xY w)zEValidates the arguments related to image building and normalize them.Nz--scriptz--python-modulezThey are required to build a training container image. Otherwise, please remove flags [{}] to directly run the `executor-image-uri`.r&   z/File '{}' is not found under the package: '{}'.z--extra-packagesz7Package file '{}' is not found under the package: '{}'.z--extra-dirsz4Directory '{}' is not found under the package: '{}'.z--output-image-urir\   )	base_name)r~   rH   ry   r   MinimumArgumentExceptionr4   r5   r6   r
   ModuleToPathospathnormpathlocal_package_pathexistsisfiler   rz   r{   isdirr|   r`   ra   rb   GenerateImageName)
r   build_args_specifiedarg_namescript_pathpackagepackage_path	directorydir_pathrc   rf   s
             r   _ValidBuildArgsOfLocalRunr     s   06	
	T//

-
-	&'	X			&!567	8	: : 
[[H))$*<*<=DK H  ggll4**DKK8:+		$BGGNN;,G

-
-DKKKK0023 3
 %%++g77##
T,,g68L77>>,'rww~~l/K//

D
K
Kt..01 1	 , OO)r)iww
T,,i8:H77>>(#277==+B//

A
H
H0023 3	 * 
((L ++L9 )::++D   //

8
?
?A    s   M 	N&M<<Nc                    | j                   }|rt        j                  j                  t	        j
                  |            }t        j                  j                  |      rt        j                  j                  |      s9t        j                  ddj                  |            t	        j                         }|| _         t        |        | S )zLValidates the arguments specified in `local-run` command and normalize them.z--local-package-pathDirectory '{}' is not found.)r   r   r   abspathr   ExpandHomeDirr   r   r   r   r4   GetCWDr   )r   args_local_package_pachwork_dirs      r   ValidateLocalRunArgsr   \  s     33wwu223JKLH77>>(#277==+B//
 
)
0
0
:< < ||~H$$D!	+r   c                 .   t         j                  j                  t        j                  |             }t         j                  j                  |      rt         j                  j                  |      s%t        j                  |dj                  |            y)zValidate the local package is valid.

  Args:
    local_package_path: str, path of the local directory to check.
    flag_name: str, indicates in which flag the path is specified.
  r   N)
r   r   r   r   r   r   r   r   r   r4   )r   rY   r   s      r   r]   r]   n  sm     WW__U001CDE(		!x)@

-
-299(CE E *Ar   )F)$__doc__
__future__r   r   r   r   googlecloudsdk.api_lib.air   r/   googlecloudsdk.callioper   googlecloudsdk.command_lib.air   r	   )googlecloudsdk.command_lib.ai.custom_jobsr
   $googlecloudsdk.command_lib.ai.dockerr   r`   googlecloudsdk.core.utilr   r   r   r   r   r    r?   rA   rE   rF   rR   r   r~   r   r   r]   r(   r   r   <module>r      s    A &  ' 	 6 . 3 4 @ F *F=;$$HN>$ GL">J" J#LEL"&;|$
Er   