
    K                         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 Z	d	 Z
 G d
 d      Z G d d      Zy)z5Utilities for building the dataproc clusters gke CLI.    )absolute_import)division)unicode_literalsN)arg_parsers)
exceptionsc                     | j                  dt        j                  ddgt        t        t        t        j                         t
        t        t        t        t        t
        t
        d      dg dd	       y )
N--poolsnameroles)r
   r   machineTypepreemptiblelocalSsdCountacceleratorsminCpuPlatformbootDiskKmsKey	locationsminmaxrequired_keysspecappendKEY=VALUE[;VALUE]a  
        Each `--pools` flag represents a GKE node pool associated with
        the virtual cluster. It is comprised of a CSV in the form
        `KEY=VALUE[;VALUE]`, where certain keys may have multiple values.

The following KEYs must be specified:

        -----------------------------------------------------------------------------------------------------------
        KEY    Type             Example                  Description
        ------ ---------------- ------------------------ ----------------------------------------------------------
        name   string           `my-node-pool`          Name of the node pool.

        roles  repeated string  `default;spark-driver`  Roles that this node pool should perform. Valid values are
                                                         `default`, `controller`, `spark-driver`, `spark-executor`.
        -----------------------------------------------------------------------------------------------------------

The following KEYs may be specified:

        ----------------------------------------------------------------------------------------------------------------------------------------------------------------
        KEY                Type             Example                                       Description
        --------------- ---------------- --------------------------------------------- ---------------------------------------------------------------------------------
        machineType        string           `n1-standard-8`                               Compute Engine machine type to use.

        preemptible        boolean          `false`                                       If true, then this node pool uses preemptible VMs.
                                                                                          This cannot be true on the node pool with the `controllers` role
                                                                                          (or `default` role if `controllers` role is not specified).

        localSsdCount      int              `2`                                           The number of local SSDs to attach to each node.

        accelerator        repeated string  `nvidia-tesla-a100=1`                         Accelerators to attach to each node. In the format NAME=COUNT.

        minCpuPlatform     string           `Intel Skylake`                               Minimum CPU platform for each node.

        bootDiskKmsKey     string           `projects/project-id/locations/us-central1    The Customer Managed Encryption Key (CMEK) used to encrypt
                                            /keyRings/keyRing-name/cryptoKeys/key-name`   the boot disk attached to each node in the node pool.

        locations          repeated string  `us-west1-a;us-west1-c`                       Zones within the location of the GKE cluster.
                                                                                          All `--pools` flags for a Dataproc cluster must have identical locations.

        min                int              `0`                                           Minimum number of nodes per zone that this node pool can scale down to.

        max                int              `10`                                          Maximum number of nodes per zone that this node pool can scale up to.
        ----------------------------------------------------------------------------------------------------------------------------------------------------------------
        typeactiondefaultmetavarhelpadd_argumentr   ArgDictstr
ArgBooleanintparsers    7lib/googlecloudsdk/command_lib/dataproc/gke_clusters.pyAddPoolsArgr)      ss    
  (335"! # #& !+1  C    c                     | j                  dt        j                  ddgt        t        t        t        j                         t
        t
        t        t        t        t        t
        t
        d      dg dd	       y )
Nr	   r
   r   )r
   r   r   r   r   localNvmeSsdCountr   r   r   r   r   r   r   r   r   a  
        Each `--pools` flag represents a GKE node pool associated with
        the virtual cluster. It is a comma-separated list in the form
        `KEY=VALUE[;VALUE]`, where certain keys may have multiple values.

The following KEYs must be specified:

        -----------------------------------------------------------------------------------------------------------
        KEY    Type             Example                  Description
        ------ ---------------- ------------------------ ----------------------------------------------------------
        name   string           `my-node-pool`          Name of the node pool.

        roles  repeated string  `default;spark-driver`  Roles that each node pool will perform.
                                                        [One Pool must have DEFAULT role] Valid values are
                                                        `default`, `controller`, `spark-driver`, `spark-executor`.
        -----------------------------------------------------------------------------------------------------------

The following KEYs may be specified:

        ----------------------------------------------------------------------------------------------------------------------------------------------------------------
        KEY                Type             Example                                       Description
        --------------- ---------------- --------------------------------------------- ---------------------------------------------------------------------------------
        machineType        string           `n1-standard-8`                               Compute Engine machine type to use.

        preemptible        boolean          `false`                                       If true, then this node pool uses preemptible VMs.
                                                                                          This Must be `false` for a node pool with the CONTROLLER role or
                                                                                          for a node pool with the DEFAULT role in no node pool has the CONTROLLER role.

        localSsdCount      int              `2`                                           The number of local SSDs to attach to each node.

        localNvmeSsdCount  int              `2`                                           The number of local NVMe SSDs to attach to each node.

        accelerator        repeated string  `nvidia-tesla-a100=1`                         Accelerators to attach to each node, in NODE=COUNT format.

        minCpuPlatform     string           `Intel Skylake`                               Minimum CPU platform for each node.

        bootDiskKmsKey     string           `projects/project-id/locations/us-central1    The Customer Managed Encryption Key (CMEK) used to encrypt
                                            /keyRings/keyRing-name/cryptoKeys/key-name`   the boot disk attached to each node in the node pool.

        locations          repeated string  `us-west1-a;us-west1-c`                       Zones within the location of the GKE cluster.
                                                                                          All `--pools` flags for a Dataproc cluster must have identical locations.

        min                int              `0`                                           Minimum number of nodes per zone that this node pool can scale down to.

        max                int              `10`                                          Maximum number of nodes per zone that this node pool can scale up to.
        ----------------------------------------------------------------------------------------------------------------------------------------------------------------
        r   r    r&   s    r(   AddPoolsAlphaArgr-   b   sv    
  (335"#&! # #( !.3  Gr*   c                   b    e Zd ZdZedd       Zed        Zed        Zed        Zed        Z	y)	GkeNodePoolTargetsParserzGParses all the --pools flags into a list of GkeNodePoolTarget messages.c           	         |D cg c]  }t         j                  | |||       }}t        j                  |       t        j	                  | |       t        j                  |       t        j                  |       |S c c}w )a  Parses all the --pools flags into a list of GkeNodePoolTarget messages.

    Args:
      dataproc: The Dataproc API version to use for GkeNodePoolTarget messages.
      gke_cluster: The GKE cluster's relative name, for example,
        'projects/p1/locations/l1/clusters/c1'.
      arg_pools: The list of dict[str, any] generated from all --pools flags.
      support_shuffle_service: support shuffle service.

    Returns:
      A list of GkeNodePoolTargets message, one for each entry in the arg_pools
      list.
    )_GkeNodePoolTargetParserParser/   _ValidateUniqueNames_ValidateRoles_ValidatePoolsHaveSameLocation_ValidateBootDiskKmsKeyPattern)dataprocgke_cluster	arg_poolssupport_shuffle_servicearg_poolpoolss         r(   r2   zGkeNodePoolTargetsParser.Parse   s    $ " "H 	!&&xh'>	@! 
 
 11%8++He<;;EB;;EBLs   A=c                     t               }| D ]<  }|j                  }||v rt        j                  dd|z        |j	                  |       > y)z'Validates that pools have unique names.r	   z#Pool name "%s" used more than once.N)setnodePoolr   InvalidArgumentExceptionadd)r<   
used_namespoolr
   s       r(   r3   z-GkeNodePoolTargetsParser._ValidateUniqueNames   sR     J]]d		11<tCE 	EnnT r*   c                 (   |syt               }|D ]A  }|j                  D ]0  }||v rt        j                  dd|z        |j	                  |       2 C | j
                  j                  j                  d      }||vrt        j                  dd      y)zAValidates that roles are exclusive and that one pool has DEFAULT.Nr	   z,Multiple pools contained the same role "%s".DEFAULTzJIf any pools are specified, then exactly one must have the "default" role.)r>   r   r   r@   rA   messagesGkeNodePoolTargetRolesValueListEntryValuesEnum)r7   r<   
seen_rolesrC   roler   s         r(   r4   z'GkeNodePoolTargetsParser._ValidateRoles   s     J**$:33G$NP P ..
   11OOGj //
  !r*   c                     | syd}| D ]E  }|j                   |j                   j                  }||}+||k7  s1t        j                  dd       y)z7Validates that all pools specify an identical location.Nr	   z(All pools must have identical locations.)nodePoolConfigr   r   r@   )r<   initial_locationsrC   r   s       r(   r5   z7GkeNodePoolTargetsParser._ValidatePoolsHaveSameLocation   si     				(''11	$'

)+33CE E r*   c                 T   | syt        j                  d      }| D ]  }|j                  	 6|j                  j                   |j                  j                  j                  G|j                  |j                  j                  j                        rwt        j                  dd       y)z>Validates that the bootDiskKmsKey matches the correct pattern.Nz>projects/[^/]+/locations/[^/]+/keyRings/[^/]+/cryptoKeys/[^/]+r	   z|bootDiskKmsKey must match pattern: projects/[KEY_PROJECT_ID]/locations/[LOCATION]/keyRings/[RING_NAME]/cryptoKeys/[KEY_NAME])recompilerL   configr   matchr   r@   )r<   boot_disk_kms_key_patternrC   s      r(   r6   z7GkeNodePoolTargetsParser._ValidateBootDiskKmsKeyPattern   s      "

H!J



''..6!!((77?&,,



$
$
3
3511 h
 	
 r*   NF)
__name__
__module____qualname____doc__staticmethodr2   r3   r4   r5   r6    r*   r(   r/   r/      si    O 2    , E E 
 
r*   r/   c                       e Zd ZdZdddddZedd       Ze	 dd       Zedd	       Zed
        Z	ed        Z
ed        Zed        Zy)r1   z@Helper to parse a --pools flag into a GkeNodePoolTarget message.rE   
CONTROLLERSPARK_DRIVERSPARK_EXECUTOR)r   
controllerzspark-driverzspark-executorc                 2    t         j                  | |||      S )a  Parses a --pools flag into a GkeNodePoolTarget message.

    Args:
      dataproc: The Dataproc API version to use for the GkeNodePoolTarget
        message.
      gke_cluster: The GKE cluster's relative name, for example,
        'projects/p1/locations/l1/clusters/c1'.
      arg_pool: The dict[str, any] generated from the --pools flag.
      support_shuffle_service: support shuffle service.

    Returns:
      A GkeNodePoolTarget message.
    )r1   _GkeNodePoolTargetFromArgPoolr7   r8   r;   r:   s       r(   r2   z_GkeNodePoolTargetParser.Parse  s#     $AA+x)@B Br*   c                     | j                   j                  dj                  ||d         t        j	                  | |d   |      t        j                  | |            S )z3Creates a GkeNodePoolTarget from a --pool argument.z{0}/nodePools/{1}r
   r   )r?   r   rL   )rF   rG   formatr1   _SplitRoles_GkeNodePoolConfigFromArgPoolrb   s       r(   ra   z6_GkeNodePoolTargetParser._GkeNodePoolTargetFromArgPool,  se     ..$++K&9IJ&228Xg=N3JL/MMh 	 / ! !r*   c                    g }t         j                  }|r1t         j                  j                         }|j                  ddi       |j	                  d      D ]r  }|j                         vrt        j                  dd|z        |j                  | j                  j                  j                  ||j                                         t |S )zFSplits the role string given as an argument into a list of Role enums.zshuffle-serviceSHUFFLE_SERVICE;r	   zUnrecognized role "%s".)r1   _ARG_ROLE_TO_API_ROLEcopyupdatesplitlowerr   r@   r   rF   rG   rH   )r7   	arg_rolesr:   r   defined_rolesarg_roles         r(   re   z$_GkeNodePoolTargetParser._SplitRoles9  s     E6LL.DDIIKm-/@ABOOC(			.1108;= 	=ll



-
-
K
KHNN,-/0	 ) Lr*   c                    | j                   j                  t        j                  | |      t        j	                  | |            }d|v r|d   j                  d      |_        || j                   j                         k7  r|S y)zECreates the GkeNodePoolConfig via the arguments specified in --pools.)rQ   autoscalingr   ri   N)rF   GkeNodePoolConfigr1   _GkeNodeConfigFromArgPool(_GkeNodePoolAutoscalingConfigFromArgPoolrm   r   r7   r;   rQ   s      r(   rf   z6_GkeNodePoolTargetParser._GkeNodePoolConfigFromArgPoolJ  s     00'AAh ,	1	1(H	E	 1 GF
 h!+.44S9f""4466mr*   c                    | j                   j                         }d|v r
|d   |_        d|v r
|d   |_        d|v r
|d   |_        d|v r$| j                   j                  |d         |_        d|v rt        j                  | |d         |_	        d|v r
|d   |_
        d|v r
|d   |_        || j                   j                         k7  r|S y	)
zACreates the GkeNodeConfig via the arguments specified in --pools.r   r   r   r,   )r   r   r   r   N)rF   GkeNodeConfigr   r   r   GkeEphemeralStorageConfigephemeralStorageConfigr1   (_GkeNodePoolAcceleratorConfigFromArgPoolr   r   r   )r7   r;   rC   s      r(   ru   z2_GkeNodePoolTargetParser._GkeNodeConfigFromArgPoolX  s     **,D !-0d !-0d("#O4dh&$,$5$5$O$O !45 %P %7d!!2[[
H^,.d8#$%56d8#$%56dx  ..00kr*   c                 V   g }|j                  d      D ]l  }d|vrt        j                  dd|z        |j                  dd      \  }}	 t        |      }|j	                  | j
                  j                  ||             n |S # t        $ r t        j                  dd|z        w xY w)zPCreates the GkeNodePoolAcceleratorConfig via the arguments specified in --pools.ri   =r	   zaaccelerators value "%s" does not match the expected "ACCELERATOR_TYPE=ACCELERATOR_VALUE" pattern.   )acceleratorCountacceleratorTypez6Unable to parse accelerators count "%s" as an integer.)rm   r   r@   r%   r   rF   GkeNodePoolAcceleratorConfig
ValueError)r7   arg_acceleratorsr   arg_acceleratoraccelerator_typecount_stringcounts          r(   r|   zA_GkeNodePoolTargetParser._GkeNodePoolAcceleratorConfigFromArgPoolr  s     L+11#6	O	#11 <>MNO 	O (7'<'<S!'D$L!::!& 0 ; 	 7&   11D 	s   
7B#B(c                     | j                   j                         }d|v r
|d   |_        d|v r
|d   |_        || j                   j                         k7  r|S y)zPCreates the GkeNodePoolAutoscalingConfig via the arguments specified in --pools.r   r   N)rF   GkeNodePoolAutoscalingConfigminNodeCountmaxNodeCountrw   s      r(   rv   zA_GkeNodePoolTargetParser._GkeNodePoolAutoscalingConfigFromArgPool  s_     ;;=F$UOf$UOf""??AAmr*   NrT   )rU   rV   rW   rX   rj   rY   r2   ra   re   rf   ru   r|   rv   rZ   r*   r(   r1   r1     s    H  $(	 B B"  =B
! 
!       2  0  r*   r1   )rX   
__future__r   r   r   rO   googlecloudsdk.callioper   r   r)   r-   r/   r1   rZ   r*   r(   <module>r      sC    < &  ' 	 / .DNHV`
 `
FG Gr*   