
    ڥ                        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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mZ ddlmZ ddlmZ ddlm Z  ddl!Z! ejD                  d      Z#dZ$d Z%dDdZ&	 	 	 dEdZ'd Z(d Z)d Z*	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dFdZ+d Z,	 dGdZ-d Z.d  Z/d! Z0	 	 	 	 	 	 	 	 dHd"Z1d# Z2d$ Z3d% Z4	 dId&Z5d' Z6d( Z7d) Z8d* Z9d+ Z:d, Z;	 	 	 	 	 	 	 	 	 dJd-Z<d. Z=d/ Z>d0 Z?d1 Z@d2 ZAd3 ZBd4 ZC	 dKd5ZDdKd6ZEd7 ZFd8 ZGd9 ZHd: ZIdLd;ZJd< ZKdKd=ZLd> ZMd? ZNd@ ZOdLdAZPdB ZQdCZRy)MzHConvenience functions for dealing with instances and instance templates.    )absolute_import)division)unicode_literalsN)	constants)containers_utils)
csek_utils)metadata_utils)utils)
zone_utils)
exceptions)flags)resource_manager_tags_utils)scope)util)log)	resources)timesz2(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)zDefault device-name for disk name [{0}] will be [{0}] because it is being mounted to a container with [`--container-mount-disk`]c                     t        j                  d|       }|r8|j                  d      }|j                  d      }|j                  d      }|||fS y)a  Gets the CPU and memory specs from the custom machine type name.

  Args:
    name: the custom machine type name for the 'instance create' call

  Returns:
    A three-tuple with the vm family, number of cpu and amount of memory for the
    custom machine type.
    custom_family, the name of the VM family
    custom_cpu, the number of cpu desired for the custom machine type instance
    custom_memory_mib, the amount of ram desired in MiB for the custom machine
      type instance
    None for both variables otherwise
  z'([a-zA-Z0-9]+)-custom-([0-9]+)-([0-9]+)         )NNN)researchgroup)namecheck_customcustom_family
custom_cpucustom_memory_mibs        4lib/googlecloudsdk/api_lib/compute/instance_utils.pyGetCpuRamVmFamilyFromCustomNamer!   0   sZ     DdK, &&q)M##A&J$**1-*&777	    c                 d    |rdj                  || |      }ndj                  | |      }|r|dz  }|S )a  Creates a custom machine type name from the desired CPU and memory specs.

  Args:
    custom_cpu: the number of cpu desired for the custom machine type
    custom_memory_mib: the amount of ram desired in MiB for the custom machine
      type instance
    ext: extended custom machine type should be used if true
    vm_type: VM instance generation

  Returns:
    The custom machine type name for the 'instance create' call
  z{0}-custom-{1}-{2}zcustom-{0}-{1}z-ext)format)r   r   extvm_typemachine_types        r    GetNameForCustomr(   H   sG     '..w
/@BL $**:7HILFL	r"   c                    | r| }n&|t         j                  |   }nt         j                  }|s|s|r[|st        j                  dd      |st        j                  dd      | rt        j
                  dd      t        ||dz  ||      }|}|S )a0  Interprets the machine type for the instance.

  Args:
    machine_type: name of existing machine type, eg. n1-standard
    custom_cpu: number of CPU cores for custom machine type,
    custom_memory: amount of RAM memory in bytes for custom machine type,
    ext: extended custom machine type should be used if true,
    vm_type:  VM instance generation
    confidential_vm_type: If not None, use default machine type based on
        confidential-VM encryption type.

  Returns:
    A string representing the URL naming a machine-type.

  Raises:
    calliope_exceptions.RequiredArgumentException when only one of the two
      custom machine type flags are used.
    calliope_exceptions.InvalidArgumentException when both the machine type and
      custom machine type flags are used to generate a new instance.
  z--custom-cpuz_Both [--custom-cpu] and [--custom-memory] must be set to create a custom machine type instance.z--custom-memoryz--machine-typez\Cannot set both [--machine-type] and [--custom-cpu]/[--custom-memory] for the same instance.i   )r   )DEFAULT_MACHINE_TYPE_FOR_CONFIDENTIAL_VMSDEFAULT_MACHINE_TYPEcalliope_exceptionsRequiredArgumentExceptionInvalidArgumentExceptionr(   )r'   r   custom_memoryr%   r&   confidential_vm_typemachine_type_namecustom_type_strings           r    InterpretMachineTyper3   _   s    6 $'!KK "66 =C99
 :; ; 99
 => > 88
 DE E *%  +	r"   c                     | j                   }| j                  }d|v r]|j                  |||      }|j                  d|fg}g }t	        | j                  ||            }	|rt        j                  |d       yyy)a  Checks that the CPU and memory ratio is a supported custom instance type.

  Args:
    compute_client: GCE API client,
    project: a project,
    zone: the zone of the instance(s) being created,
    machine_type_name: The machine type of the instance being created.

  Returns:
    Nothing. Function acts as a bound checker, and will raise an exception from
      within the function if needed.

  Raises:
    utils.RaiseToolException if a custom machine type ratio is out of bounds.
  custom)machineTypeprojectzoneGet)requestserrors_to_collectzCould not fetch machine type:)error_messageN)messagesapitools_clientComputeMachineTypesGetRequestmachineTypeslistMakeRequestsr
   RaiseToolException)
compute_clientr7   r8   r1   r=   compute	mt_get_pbmt_get_reqserrors_s
             r    CheckCustomCpuRamRatiorJ      s      $$(**'""66%wT 7 CI((%;<KF 	## F 	$ 	<	=A 
 ?A  #r"   c           	         |t         j                  }|d}t        j                  t              }|D ]  }|j                  d      }t        |      dk(  r|}|}nIt        |      dk(  rt        j                  dd      t        j                  ddj                  |            |dk7  r.t        j                  |      st        j                  dd	|z         t         j                  j                  ||g      }||   j                  |        |s|dk7  r| j                  |g 
      gS g }t!        t#        j$                  |            D ]0  \  }}|j'                  | j                  |t!        |      
             2 |S )zBReturns a list of ServiceAccount messages corresponding to scopes.default=r   r   z--scopeszFlag format --scopes [ACCOUNT=]SCOPE,[[ACCOUNT=]SCOPE, ...] is removed. Use --scopes [SCOPE,...] --service-account ACCOUNT instead.zM[{0}] is an illegal value for [--scopes]. Values must be of the form [SCOPE].z--service-accountz>Invalid format: expected default or user@domain.com, received )emailscopes)r   DEFAULT_SCOPEScollectionsdefaultdictrA   splitlenr,   r.   r$   EMAIL_REGEXmatchSCOPESgetextendServiceAccountsortedsix	iteritemsappend)	r=   rO   service_accountaccounts_to_scopesr   partsaccount	scope_uriress	            r    CreateServiceAccountMessagesre      s{   ^%%FO"..t4eKKE
5zQgi	Uq88
   88
 &-) )
 )#K,=,=o,N88

J
    $$Y<Iw&&y17 : 
Oy0##/"#EFF
#.@ ABogvJJx&&WVF^&LM C	*r"   c                 H    |r| j                   j                  |      }|S d}|S )z*Create on-host-maintenance message for VM.N)
Scheduling OnHostMaintenanceValueValuesEnum)r=   maintenance_policyon_host_maintenances      r    CreateOnHostMaintenanceMessagerk      s5    "--NN 
 	r"   c                    t        | |      }|s|	dk(  r| j                  d|d      }n| j                  ||      }|	r | j                  j                  |	      |_        |
r | j                  j	                  |
      |_        || j                  |      |_        || j                  |      |_        |U| j                         |_
        d|v r|d   |j                  _        d|v r$| j                  |d         |j                  _        |rt        j                  |      |_        |r||_        |t#        |      |_        |r||_        |r
|d	z  |_        |r | j                  j+                  |      |_        |r||_        |r||_        || j3                  |
      |_        |||_        || j                  |      |_        |S )z!Create scheduling message for VM.SPOTFT)automaticRestartonHostMaintenancepreemptible)rn   ro   secondsenabledmaxDurationi  )discardLocalSsd)rk   rg    ProvisioningModelValueValuesEnumprovisioningModel(InstanceTerminationActionValueValuesEnuminstanceTerminationActionDurationmaxRunDurationlocalSsdRecoveryTimeoutSchedulingGracefulShutdowngracefulShutdownrs   rt   r   FormatDateTimeterminationTimenodeAffinitiesintminNodeCpuslocationHintmaintenanceFreezeDurationHours"MaintenanceIntervalValueValuesEnummaintenanceIntervalhostErrorTimeoutSecondsavailabilityDomainSchedulingOnInstanceStopActiononInstanceStopActionskipGuestOsShutdownpreemptionNoticeDuration)r=   ri   rp   restart_on_failurenode_affinitiesmin_node_cpulocation_hintmaintenance_freeze_durationmaintenance_intervalprovisioning_modelinstance_termination_actionhost_error_timeout_secondsmax_run_durationtermination_timelocal_ssd_recovery_timeoutavailability_domaingraceful_shutdown+discard_local_ssds_at_termination_timestampskip_guest_os_shutdownpreemption_notice_durationrj   
schedulings                         r    CreateSchedulingMessager      s2   : 7x7IK&&0$$- % J
 $$+- % /J <<=OP   !DD'	
 ( ! ( 1 1:J 1 KJ+)1):):* *; *J& ""*"E"E"GJ%%,=i,Hj!!)))080A0A#M2 1B 1j!!- !&!5!56F!GJ /J .J+J #t+ - >> 	" "  )CJ&$7J!0<&.&M&MC 'N 'J# '%;J"+*2*;*;* +< +J' 
r"   c                 .    | j                  |||      }|S )z-Create shieldedInstanceConfig message for VM.)enableSecureBoot
enableVtpmenableIntegrityMonitoring)ShieldedInstanceConfig)r=   enable_secure_bootenable_vtpmenable_integrity_monitoringshielded_instance_configs        r    #CreateShieldedInstanceConfigMessager   g  s+    
 &<<) ; = =
 
"!r"   c                 *    | j                  |      }|S )z7Creates shieldedInstanceIntegrityPolicy message for VM.)updateAutoLearnPolicy)ShieldedInstanceIntegrityPolicy)r=   update_auto_learn_policy"shielded_instance_integrity_policys      r    ,CreateShieldedInstanceIntegrityPolicyMessager   t  s&     (0'O'O4 (P (6$ 
,+r"   c           	      0   | r|syddg}ddg}| j                  dd      }| j                  dd      }|r0||vr,t        j                  dd	| d
dj                  |       d      |r1||vr,t        j                  dd| d
dj                  |       d      yy)a  Validates flags specifying SVSM config.

  Args:
    svsm_args: The flags specifying SVSM config.
    support_snp_svsm: Whether SVSM is supported.

  Returns:
    Nothing. Function acts as a validator, and will raise an exception from
      within the function if needed.

  Raises:
    calliope_exceptions.RequiredArgumentException when the flags are not
      specified or are not valid.
  N	EPHEMERAL	NO_CC_TPM
RESTRICTEDUNRESTRICTEDtpmsnp-irqz--svsm-configz#Unexpected confidential TPM type: [z]. Legal values are [z, z].zUnexpected SEV SNP IRQ mode: [)rX   r,   r.   join)	svsm_argssupport_snp_svsmtpm_choicessnp_irq_choicesr   snp_irqs         r    ValidateSvsmConfigr   ~  s      
*
k*+!>2/eT"#MM)T*'S#

6
6
-cU 3IIk"#2	' 
 /

6
6
(	 2IIo&'r	+  0Wr"   c                    t        | d      r| j                  d      r|syt        | j                  |       | j                  r| j                  j	                  dd      nd}| j                  r| j                  j	                  dd      nd}|j
                  j                  |      }|j
                  j                  |      }|j                  ||      S )z2Create confidentialParavisorConfig message for VM.svsm_configNr   !CONFIDENTIAL_TPM_TYPE_UNSPECIFIEDr   SEV_SNP_IRQ_MODE_UNSPECIFIED)confidentialTpmTypesevSnpIrqMode)hasattrIsSpecifiedr   r   rX   ConfidentialParavisorConfig"ConfidentialTpmTypeValueValuesEnumSevSnpIrqModeValueValuesEnum)argsr=   r   r   r   confidential_tpm_typesev_snp_irq_modes          r    (CreateConfidentialParavisorConfigMessager     s     $
&d.>.>}.MT%%'78 
		 5"EF.  
		 9&DE) 
 **MM
  **GG
 
 
	-	-/$ 
. 
 r"   c                 t   d}d}d}t        |d      r7|j                  d      r&t        |j                  t              r|j                  }|rt        |d      rx|j                  d      rgt        |j
                  t        j                        rC| j                  j                  |j
                        }|sd| j                  j                  v rd}d}t        || |      }||| j                  ||      }|S || j                  |      }|S |t        j                  dd      || j                  |	      }|S )
z1Create confidentialInstanceConfig message for VM.Nconfidential_computeconfidential_compute_typeTDX)confidentialInstanceTypeconfidentialParavisorConfig)r   z--confidential-compute-typezEConfidential compute type must be specified when using --svsm-config.)enableConfidentialCompute)r   r   
isinstancer   boolr   r\   string_typesConfidentialInstanceConfig'ConfidentialInstanceTypeValueValuesEnumr   r,   r.   )	r=   r   !support_confidential_compute_type%support_confidential_compute_type_tdxr    confidential_instance_config_msgenable_confidential_computeconfidential_instance_type!confidential_paravisor_config_msgs	            r    !CreateConfidentialInstanceMessager     s   
 &*" $#d*+
-.**D1"&";";'d/0
23//1A1AB++	0	0**
, 
 2//44	6 %)!#' &N
H&'# !,
+
7'/'J'J!;$E (K ($& 
*) "-'/'J'J!; (K ($ 
*) )4

6
6%	 
 #.'/'J'J"= (K ($ 
*)r"   c	                    | j                         }	|||	_        |||	_        |||	_        |||	_        |||	_        |.| j                   j                  |j                               |	_        |||	_	        |||	_
        |	S )z7Create AdvancedMachineFeatures message for an Instance.)AdvancedMachineFeaturesenableNestedVirtualizationthreadsPerCorenumaNodeCountvisibleCoreCountenableUefiNetworking(PerformanceMonitoringUnitValueValuesEnumupperperformanceMonitoringUnitenableWatchdogTimer	turboMode)
r=   enable_nested_virtualizationthreads_per_corenuma_node_countvisible_core_countenable_uefi_networkingperformance_monitoring_unitenable_watchdog_timer
turbo_modefeaturess
             r    $CreateAdvancedMachineFeaturesMessager     s     --/(!-*FH'!.H ,H# 2H'$:H! ,)1)I)I)r)r#))+*H& &#8H #H	/r"   c                     |t         j                  j                  k(  r*| j                  |d|t	        j
                  |      d      S | j                  |d||d      S )aj  Parses disk resources.

  Project and zone are ignored if a fully-qualified resource name is given, i.e.
    - https://compute.googleapis.com/compute/v1/projects/my-project
          /zones/us-central1-a/disks/disk-1
    - projects/my-project/zones/us-central1-a/disks/disk-1

  If project and zone cannot be parsed, we will use the given project and zone
  as fallbacks.

  Args:
    resources: resources.Registry, The resource registry
    name: str, name of the disk.
    project: str, project of the disk.
    zone: str, zone of the disk.
    type_: ScopeEnum, type of the disk.

  Returns:
    A disk resource.
  compute.regionDisksr7   region
collectionparamscompute.disksr7   r8   )compute_scopes	ScopeEnumREGIONParser
   ZoneNameToRegionName)r   r   r7   r8   type_s        r    ParseDiskResourcer  /  ss    * n&&---??(006
    ??"
   r"   c                    	 | j                  |j                  d      }|r|S 	 	 | j                  |j                  d      }|r|S 	 t        j
                  dj                  |j                  |j                              # t        j                  t        j                  f$ r Y w xY w# t        j                  t        j                  f$ r Y w xY w)a  Parses the source disk resource of an AttachedDisk.

  The source of an AttachedDisk is either a partial or fully specified URL
  referencing either a regional or zonal disk.

  Args:
    resources: resources.Registry, The resource registry
    attached_disk: AttachedDisk

  Returns:
    A disk resource.

  Raises:
    InvalidResourceException: If the attached disk source cannot be parsed as a
        regional or zonal disk.
  r   )r   r   z^Unable to parse disk's source: [{0}] of device name: [{1}], try using `--device-name` instead.)r  sourcecloud_resources WrongResourceCollectionExceptionRequiredFieldOmittedExceptionInvalidResourceExceptionr$   
deviceName)r   attached_diskdisks      r    !ParseDiskResourceFromAttachedDiskr  V  s    "
	??)>  D k 	??=//O?LDk  	00""(&




"
"#	  6633
 	 			 6633
 	 			s"    B   B)  #B&%B&)#CCc           
         |rt        t        |D cg c]  }|j                  d|      |k(   c}      r| j                  d      s*t        j                  t
        j                  |             |S | j                  d      |k7  r5t        j                  ddj                  || j                  d                  | j                  d      S c c}w )z4Helper method to get device-name for a disk message.r   zdevice-namez--container-mount-diskz{Attempting to mount disk named [{}] with device-name [{}]. If being mounted to container, disk name must match device-name.)	filterr   rX   r   warning&_DEFAULT_DEVICE_NAME_CONTAINER_WARNINGr$   r,   r.   )r  r   container_mount_diskds       r    GetDiskDeviceNamer    s    f
2FG2FQQUU64 D(2FG
 88M"	kk8??EFk	-	 D	(88
"J6$/0	  
-	   Hs   C	
c                     |t         j                  j                  k(  r |dk7  rd}||d}n7d}t        |      }||d}n$|t         j                  j                  k(  rd}||d}| j                  |      }|S )3Parses disk type reference based on location scope.r   zcompute.diskTypesr   zcompute.regionDiskTypesr   r   )r   r  ZONEGetRegionFromZoner  r  )	r   	disk_typer7   locationr   replica_zone_cntr   r   disk_type_refs	            r    ParseDiskTyper     s     n&&+++1&j"H5f,j"8,h"h7f((///*J H5F//Jv " 7-	r"   c                 d    dj                  | j                  d      dd       j                         S )z1Returns the GCP region that the input zone is in.-N)r   rS   lower)r8   s    r    r  r    s)    	$**S/#2&	'	-	-	//r"   c                 <    d}||d}| j                  |||      }|S )r  zcompute.storagePoolsr   r   )r  )r   storage_poolr7   r  r   r   storage_pool_refs          r    ParseStoragePoolr(    s4    %*1&__z& %  
r"   c                 &    t        d | D              S )z=Returns True if the user has specified an existing boot disk.c              3   @   K   | ]  }|j                  d d        yw)bootFN)rX   ).0r  s     r    	<genexpr>z&UseExistingBootDisk.<locals>.<genexpr>  s     7TXXfe$s   )any)diskss    r    UseExistingBootDiskr0    s    	77	77r"   c                 \    t        |D cg c]  }| j                  |       c}      S c c}w N)r.  r   )r   destsdests      r    IsAnySpecifiedr5    s*    	7dt$7	887s   )c                     | j                  d      sy |j                  | |t        j                  j                  j
                        }|j                         S )Nsource_instance_template)default_scope)r   ResolveAsResourcer   compute_scoper  GLOBALSelfLink)r   r   source_instance_template_argrefs       r    GetSourceInstanceTemplater?    sP    			4	5$66
IU%8%8%B%B%I%I 	7 	# 
r"   c                 
    | d uS r2   )r7  s    r    GetSkipDefaultsrB    s     
"	--r"   c                 n   d}|r!t        j                  | |j                  |      }d}|r| j                  }d}t	        | d      r| j
                  }d}t	        | d      r| j                  d      r| j                  }d}t	        | d      r| j                  d      r| j                  }d}t	        | d      r| j                  d      r| j                  }d}t	        | d      r| j                  d      r| j                  }d}|rt	        | d      r| j                  }d}|rt	        | d      r| j                  }d}|r)t	        | d	      r| j                  d	      r| j                  }t        | |	      }d}|rt	        | d
      r| j                  }d}|rt	        | d      r| j                   }d}|r| j#                  d      r| j$                  }d}| j#                  d      rt	        | d      r| j&                  }d}|
r| j#                  d      r| j(                  }d}|rt	        | d      r| j*                  }|r$t-        | dddd      s|s|s|s|s|s|s	|s|s|s|syt/        di d|j                  d| j0                  d| j2                  d|d|d|d|d|d|d|d|d|d|d
|d	|d|d|d|d|d|S )z>Generate a Scheduling Message or None based on specified args.Nr   r   r   r   r   r   r   r   r   r   r   r   r   r   ri   rp   r=   r   r   r   rA  )sole_tenancy_util%GetSchedulingNodeAffinityListFromArgsr=   r   r   r   r   r   r   r   r   r   r   r   ExtractGracefulShutdownFromArgsr   r   IsKnownAndSpecifiedr   r   r   r   r5  r   ri   rp   )r   clientskip_defaultssupport_node_affinitysupport_min_node_cpusupport_node_project"support_host_error_timeout_secondssupport_max_run_duration"support_local_ssd_recovery_timeoutsupport_graceful_shutdownsupport_skip_guest_os_shutdown"support_preemption_notice_durationr   r   r   freeze_durationr   r   r   r   r   r   r   r   r   r   r   r   r   s                                r    GetSchedulingrT    s    /'MMfoo35O,$$L-T?#&&M/T01d6F6F#7%66O
"&"2"23I"J44d()
+,00 $d12
45"&"B"B#'G
(-*!%!@!@'$0B"C,,#'G
(-*.2.>.>
&/(!%!@!@5
% '$0B"C,,04-'
9# 	88 0 	$223GH00	34
!: 22#(@(@) "88#'G
(- "&!@!@ 

'


 !("((	  

00
 ""
 ,	

 &
  
 "
 #2
 0
 ,
 #>
 "<
 (
 (
 "<
  .!
" *#
$ 3^%
& 4'
( "<)
 r"   c                     | j                   rd }n| j                  }|rt        | dddd      sg S t        |j                  | j
                  rg |      S | j                  |      S )NrO   	no_scopesr_   no_service_account)r=   rO   r_   )rW  r_   r5  re   r=   rV  rO   )r   rH  rI  r_   s       r    GetServiceAccountsrX  j  sl    	O**ON
Hk#46JLI	%>>R%
' ''+{{%
' 'r"   c                     t        j                  |j                  | j                  | j                        }t        j                  |       |S )Nmetadatametadata_from_file)r	   ConstructMetadataMessager=   r[  r\  r   ValidateUserMetadata)r   rH  user_metadatas      r    GetValidatedMetadatar`  x  s?     99oo}}002- ''6	r"   c                     |rt        | dd      sy t        j                  |j                  | j                  | j
                        S )Nr[  r\  rZ  )r5  r	   r]  r=   r[  r\  )r   rH  rI  s      r    GetMetadatarb    s?    
z+?
@22224 4r"   c                     t        j                  | j                        }t        j                  || j                         |S r2  )r
   	BytesToGbboot_disk_sizeWarnIfDiskSizeIsTooSmallboot_disk_type)r   boot_disk_size_gbs     r    GetBootDiskSizeGbri    s4    ood&9&9:  !2D4G4GH	r"   c                     t         j                  j                  | |j                  t	        j
                  |            }t        j                  |      }|j                  |       |S )N)scope_lister)	r   INSTANCES_ARGr9  r   compute_flagsGetDefaultScopeListerr   ZoneResourceFetcherWarnForZonalCreation)r   rH  holderinstance_refszone_resource_fetchers        r    GetInstanceRefsrt    s_    %%77
 66v> 8 @-
 %88@,,];	r"   c                     |j                  | |j                        }t        j                  j	                  | j
                  d      }t        j                  |||j                        }|S )NF)allow_rsa_encrypted)r9  r   r   CsekKeyStoreFromFile"source_machine_image_csek_key_fileMaybeLookupKeyMessager>   )r   source_imagerD   rq  machine_image_ref	csek_keysdisk_key_or_nones          r    GetSourceMachineImageKeyr    sh    "44T6;K;KL%%..
--5 / J)55"N$B$BD	r"   c                 (    | xs t        | ddd      S )Nr'   r   r/   )r5  r   rI  s     r    CheckSpecifiedMachineTypeArgsr    s"    
 N
~|_
MOr"   c                 X    t        | |      }t        ||||       t        |||||      }|S )z@Create a machine type URI for given args and instance reference.)CreateMachineTypeNamerJ   ParseMachineType)	r   rD   resource_parserr7   r  r   r0   r1   machine_type_uris	            r    CreateMachineTypeUrir    sA     ,D2FG (<MN%o7H&-x@	r"   c                     | j                   }| j                  }| j                  }t        | dd      }t        | dd      }t	        ||||||      }|S )zACreate a machine type name for given args and instance reference.custom_vm_typeNcustom_extensions)r'   r   r/   r%   r&   r0   )r'   r   r/   getattrr3   )r   r0   r'   r   r/   r&   r%   r1   s           r    r  r    sh     "",*$$-D*D1')40# +!
/1 
r"   c                     |t         j                  j                  k(  rd}||d}n$|t         j                  j                  k(  rd}||d}| j	                  |      j                         }|S )z/Returns the location-specific machine type uri.zcompute.machineTypesr   zcompute.regionMachineTypesr   r   r   r  r  r  r  r<  )r  r1   r7   r  r   r   r   r  s           r    r  r    sv     n&&+++'J (3F((///-J H5F$**Jv + ??Gxz 	r"   c                    d}| j                  d      r&| j                  rt        j                  j                  }|rO| j                  d      r>| j
                  2t        t        j                  | j
                  j                               }|S )z1Returns the CONFIDENTIAL_VM_TYPES of the machine.Nr   r   )r   r   r   CONFIDENTIAL_VM_TYPESSEVr   r  r   )r   r   r0   s      r    GetConfidentialVmTyper    s}    	,-$2K2K$::>>'


6
7

(
(
4"9#B#B#'#A#A#G#G#IK 
r"   c                 B    |r| j                  d      sy | j                  S )Ncan_ip_forward)r   r  r  s     r    GetCanIpForwardr    s"    4++,<=			r"   c                 h    | j                   r&|j                  j                  | j                         S y )N)items)tagsr=   Tags)r   rH  s     r    GetTagsr    s(    	YY??dii00	r"   c           
      R   |j                   j                  j                  }|r |j                   j                  j                  }| j                  rS |t        t        j                  | j                              D cg c]  \  }}|j                  ||       c}}      S yc c}}w )z%Gets labels for the instance message.keyvalueadditionalPropertiesN)	r=   InstanceLabelsValueInstancePropertieslabelsr[   r\   r]   AdditionalProperty)r   rH  instance_propertieslabels_valuer  r  s         r    	GetLabelsr    s    ))55,??55AAL	[[ t{{!;<.<JC 	''Cu'=<.   
	.s   <B#
c                     |t         j                  j                  k(  rd}||d}n$|t         j                  j                  k(  rd}||d}|j	                  |       j                         }|S )z5Returns accelerator type ref based on location scope.zcompute.acceleratorTypesr   zcompute.regionAcceleratorTypesr   r   r  )accelerator_type_namer  r7   r  r   r   r   accelerator_types           r    ParseAcceleratorTyper  
  sw     n&&++++J (3F((///1J H5F$**
6 + CCK8: 	r"   c                     | rS|rQ|rO|r'|j                  |d| |d      }|j                         S |j                  |dd| i      }|j                         S y)z-Returns snapshot URI based on location scope.zcompute.regionSnapshotsr   r   zcompute.snapshotsr7   Nr  r<  )user_projectsnapshotr  r   snapshot_refs        r    ResolveSnapshotURIr    sw    h?$**
.)V< + l
 ""$$"((&<( ) *L   ""	r"   c                 \    | r*|r(|r&|j                  |dd| i      }|j                         S y )Nzcompute.instantSnapshotsr7   r   r  )r  instant_snapshotr  instant_snapshot_refs       r    ResolveInstantSnapshotURIr  +  sB    &?*00-<( 1 
  ((**	r"   c                    | j                  d      r|j                  j                  j                  }d}g }d|j                  i}|r(|j                  |j                  |j                  d       | j                  dk(  r|j                  }n=| j                  |v r#|| j                     }t        }| j                  g}n|j                  }|j                  j                  ||xs d|      S y)z=Returns the message of reservation affinity for the instance.reservation_affinityNspecific)zspecific-then-any-reservationzspecific-then-no-reservationnone)consumeReservationTyper  values)r   r=   ReservationAffinity%ConsumeReservationTypeValueValuesEnumSPECIFIC_RESERVATIONupdateSPECIFIC_THEN_ANY_RESERVATIONSPECIFIC_THEN_NO_RESERVATIONr  NO_RESERVATION_RESERVATION_AFFINITY_KEYreservationANY_RESERVATION)r   rH   support_specific_then_x_affinity	type_msgsreservation_keyreservation_valuesspecific_affinities_mapreservation_types           r    GetReservationAffinityr  6  s   	,-++	.	.  O 	I22 ($$55 44& 	   F*"11		"	"&=	=01J1JK 2o ,,-"22??../#t! / # #
 
r"   c                     t        | dg       }|j                  j                         }|D ]O  }|j                  dd      j	                         }|s&|j                  j                  j                  |      |_        Q |S )z6Get NetworkPerformanceConfig message for the instance.network_performance_configsztotal-egress-bandwidth-tier )r  r=   NetworkPerformanceConfigrX   r   'TotalEgressBandwidthTierValueValuesEnumtotalEgressBandwidthTier)r   rH  network_perf_argsnetwork_perf_configsconfig
total_tiers         r    GetNetworkPerformanceConfigr  c  s}     d$A2FAAC!f92>DDFJ6<oo6^6^  7G  7G
73 " 
r"   c                     d}|rit        | d      r| j                  d      rd| j                  i}t        | d      r2| j                  d      r!|d| j                  i}|S | j                  |d<   |S )z%Extracts graceful shutdown from args.Nr   rs   graceful_shutdown_max_durationrt   )r   r   r   r  )r   rP  r   s      r    rF  rF  r  s     t()d.>.>/ %d&<&<=t564;K;K(< 
	"*D,O,OP 
 ,0+N+N-(	r"   c           
         |j                   j                         }| j                  d      rt        j                  | j
                        }|n|j                   j                  j                  } |t        t        j                  |            D cg c]  \  }}|j                  ||       c}}      |_        | j                  d      rmt        | d      r | j                  d      r| j                  dk7  rt        j                   dd      |j                   j#                  | j$                  	      |_        |S c c}}w )
z)Create a Params message for the instance.resource_manager_tagsr  r  request_valid_for_durationr   
FLEX_STARTz--request_valid_for_durationzS[--request_valid_for_duration] is only supported for FLEX_START provisioning model.rq   )r=   InstanceParamsrG  r   GetResourceManagerTagsr  ResourceManagerTagsValuer[   r\   r]   r  resourceManagerTagsr   r   r   r,   r.   rz   r  requestValidForDuration)r   rH  r   ret_resource_manager_tagsresource_manager_tags_valuer  r  s          r    CreateParamsr    sB    ??))+&	56#::&&	
 
 !,
//
(
(
A
A " $?
 !'s}}5N'O P	  !Q*#u *<< =  !Q	 $f  
:;D./ 45""l288
(!  &,__%=%=// &> &F" 
-1 s   D;
z'compute.googleapis.com/reservation-name)FF)TFN)NNNNNNNNNNNNNNNN)T)NNNNNNNN)r   )	FTFTFFFFFr2  )F)S__doc__
__future__r   r   r   rQ   r   googlecloudsdk.api_lib.computer   r   r   r	   r
   r   googlecloudsdk.callioper   r,   "googlecloudsdk.command_lib.computer   rm  r   r   r   ,googlecloudsdk.command_lib.compute.instances/googlecloudsdk.command_lib.compute.sole_tenancyr   rD  googlecloudsdk.corer   r   r	  googlecloudsdk.core.utilr   r\   compilerU   r  r!   r(   r3   rJ   re   rk   r   r   r   r   r   r   r   r  r  r  r   r  r(  r0  r5  r?  rB  rT  rX  r`  rb  ri  rt  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rF  r  r  rA  r"   r    <module>r     s   O &  '  	 4 ; 5 9 0 5 E E J F > U # < * 
bjjNO= '
04 "!&.2;|AD*Z  $ $##04#)nb
" KO,#LD8*z "& $+\$N-`!, FG(0
8
9.  '+"',##(',Nb'4O /3&* 
&*Z*(V F r"   