
                           S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSKJ	r	  SSKJ
r  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ
r   SSK!J"r"  SSK!J#r#  SSK!J
r$  SSK%J&r&  SSK'J(r(  SSK)J*r+  SSK,J*r-  SSK.J/r/  SSK.J
r
  SSK.J0r0  SSK.J1r1  SSK.J2r2  SSK.J3r3  SSK.J4r4  SSK5J6r6  SSK7J	r8  SSK9r9Sr:S r;S!r<S"r=S#r>S$r?S%r@S&rAS'rBS(rCS)rDS*rES+rFS,rGS-rHS.rIS/rJS0rK\L" 1 S1k5      rM\D\E4rN\D\F4rO\D\F4rP\G\I\H4rQ\G\I\H4rR\G\I\H4rSS2rTS3S4S5S6S7.rUS4S5S8S9.rV " S: S;\R                  5      rX " S< S=\R                  5      rZ " S> S?\
R                  5      r\ " S@ SA\
R                  5      r] " SB SC\
R                  5      r^ " SD SE\_5      r`  SSF jraSG rbSH rcSI rdSJ reSK rfSL rgSM rhSSN jriSSO jrjSSP jrk  SSQ jrlSR rm\C4SS jrnSST jroSU rpSV rqSW rrSX rsSY rtSZ ruS[ rvS\ rwS] rx\C4S^ jry\C4S_ jrzS` r{ SSa jr|Sb r}Sc r~SSSSd S4Se jrSf rSg rSh rSi rSj rSk rSl rSSm jrSSn jrSo rSSp jrSq rSr rSSs jrSt rSu rSv rSSw jrSx rSy rSz rS{ rS| rS} rS~ rS rg)z?Utilities for running Daisy builds on Google Container Builder.    )absolute_import)division)unicode_literalsN)encoding)
exceptions)	HttpError)HttpNotFoundError)cloudbuild_util)logs)projects_api)instance_utils)utils)
enable_api)storage_api)storage_util)apis)arg_parsers)base)docker_util)	execution)util)config)execution_utils)log)
properties)requests)	resources)
console_ioz4gcr.io/{gcp_project}/{executable}:{docker_image_tag}zN{region}-docker.pkg.dev/{gcp_project}/wrappers/{executable}:{docker_image_tag}zcompute-image-importzcompute-image-toolsgce_vm_image_importgce_vm_image_exportgce_ovf_importgce_windows_upgradegce_onestep_image_importreleasezroles/compute.storageAdminzroles/storage.objectViewerzroles/storage.objectAdminzroles/compute.adminzroles/iam.serviceAccountUserz$roles/iam.serviceAccountTokenCreatorzroles/storage.adminzroles/editor>   storage.buckets.getstorage.objects.getstorage.buckets.liststorage.objects.createstorage.objects.delete)
asia-east1asia-northeast1zasia-southeast1zaustralia-southeast1zeurope-west1zeurope-west2zeurope-west3europe-west4zeurope-west6znorthamerica-northeast1zsouthamerica-east1us-central1zus-east1zus-east4zus-west1europer-   r,   r+   )eunam4eur4asia1r*   )usr.   asiac                       \ rS rSrSrS rSrg)FilteredLogTailer   z3Subclass of GCSLogTailer that allows for filtering.c                    U R                   (       aa  UR                  5       nU HJ  nU R                    H7  nUR                  U5      (       d  M  U R                  R	                  U5          MH     ML     gU R                  R	                  U5        g)z0Override PrintLogLine method to use self.filter.N)filter
splitlines
startswithoutPrint)selftextoutput_lineslinematchs        1lib/googlecloudsdk/api_lib/compute/daisy_utils.py_PrintLogLineFilteredLogTailer._PrintLogLine   sa    {{__&l$[[E__U##HHNN4  !  hhnnT     N)__name__
__module____qualname____firstlineno____doc__rD   __static_attributes__rG   rF   rC   r6   r6      s
    ;
rF   r6   c                   "    \ rS rSrSrSS jrSrg)CloudBuildClientWithFiltering   z3Subclass of CloudBuildClient that allows filtering.Nc                 H   U R                  U5      n[        R                  U5      nX5l        U R                  R
                  R                  nUR                  UR                  /nU" S5      nSn	Sn
UR                  U;   a]  U
(       a   UR                  5         [&        R(                  " U5        U R                  U5      nX-  n	U" U	5      nUR                  U;   a  M]  U
(       a   UR                  SS9  U$ U$ ! [        R                   aO  n[        R                  " SR                  [         R"                  " UR$                  5      5      5        Sn
 SnANSnAff = f! [        R*                   aN  n[        R                  " SR                  [         R"                  " UR$                  5      5      5         SnAU$ SnAf[        R                   aN  n[        R                  " SR                  [         R"                  " UR$                  5      5      5         SnAU$ SnAff = f)a  Stream the logs for a build using allowlist filter.

Args:
  build_ref: Build reference, The build whose logs shall be streamed.
  backoff: A function that takes the current elapsed time
    and returns the next sleep length. Both are in seconds.
  output_filter: List of strings, The output will only be shown if the line
    starts with one of the strings in the list.

Raises:
  NoLogsBucketException: If the build does not specify a logsBucket.

Returns:
  Build message, The completed or terminated build as read for the final
  poll.
r   TzDFailed to fetch cloud build logs: {}. Waiting for build to complete.FN)is_lastz%Failed to fetch cloud build logs: {}.)GetBuildr6   	FromBuildr9   messagesBuildStatusValueValuesEnumQUEUEDWORKINGstatusPollapitools_exceptionsr   r   warningformatencoding_utilDecodecontenttimesleepCommunicationError)r>   	build_refbackoffoutput_filterbuild
log_tailerstatusesworking_statusesseconds_between_pollseconds_elapsedpoll_build_logses               rC   StreamWithFilter.CloudBuildClientWithFiltering.StreamWithFilter   s   " MM)$E",,U3J%}}""88H
 #1:OO
,,*
*		"
//
 jj%&mmI&e-o$_5 ,,*
*( 
% L5L? #,, 	"
++!6-"6"6qyy"AB "/	"& !33 
3::$$QYY/	
 	
 L !** 
3::$$QYY/	
 	

 L
s?   	C9 &E 9EAEEH!3AF<<H!AHH!rG   N)rH   rI   rJ   rK   rL   rp   rM   rG   rF   rC   rO   rO      s    ;ArF   rO   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )FailedBuildException   z*Exception for builds that did not succeed.c                 p   > [         [        U ]  SR                  UR                  UR
                  S95        g )Nz+build {id} completed with status "{status}")idrZ   )superrt   __init__r^   rw   rZ   )r>   rh   	__class__s     rC   ry   FailedBuildException.__init__   s7    	

FMM%,, N 0 1rF   rG   )rH   rI   rJ   rK   rL   ry   rM   __classcell__)rz   s   @rC   rt   rt      s    21 1rF   rt   c                       \ rS rSrSrSrg)SubnetExceptioni  z$Exception for subnet related errors.rG   NrH   rI   rJ   rK   rL   rM   rG   rF   rC   r~   r~     s    ,rF   r~   c                       \ rS rSrSrSrg)DaisyBucketCreationExceptioni  z,Exception for Daisy creation related errors.rG   Nr   rG   rF   rC   r   r     s    4rF   r   c                        \ rS rSrSrSrSrSrg)ImageOperationi	  z"Enum representing image operation.importexportrG   N)rH   rI   rJ   rK   rL   IMPORTEXPORTrM   rG   rF   rC   r   r   	  s    *&&rF   r   c           	         [         R                  " U 5      n/ SQnU H  n[        R                  " UR                  U5      (       a  M+  SR                  U5      n[        R                  " USSS9n	U	(       a#  [        R                  " UR                  U5        M|  [        R                  " SR                  U5      5        M     SR                  UR                  5      n
U(       a  SR                  U5      n
S	R                  UR                  5      nU(       a  SR                  U5      n [         R                  " U 5      n[        X5      n[!        U U
U["        5        [%        U U
U['        U5      5        [        X5      n[(        U;  a  [%        XUU5        gg! [        R                   a)    [        R                  " S
R                  XX5      5         gf = f)a  Check for needed IAM permissions and prompt to add if missing.

Args:
  project_id: A string with the id of the project.
  cloudbuild_service_account_roles: A set of roles required for cloudbuild
    service account.
  compute_service_account_roles: A set of roles required for compute service
    account.
  custom_cloudbuild_service_account: Custom cloudbuild service account
  custom_compute_service_account: Custom compute service account
)zcloudbuild.googleapis.comzlogging.googleapis.comzcompute.googleapis.comzVThe "{0}" service is not enabled for this project. It is required for this operation.
z&Would you like to enable this service?T)throw_if_unattendedzIf import fails, manually enable {0} before retrying. For instructions on enabling services, see https://cloud.google.com/service-usage/docs/enable-disable.z1serviceAccount:{0}@cloudbuild.gserviceaccount.comzserviceAccount:{0}z8serviceAccount:{0}-compute@developer.gserviceaccount.comzYour account does not have permission to check roles for the service account {0}. If import fails, ensure "{0}" has the roles "{1}" and "{2}" has the roles "{3}" before retrying.N)r   Getservices_apiIsServiceEnabled	projectIdr^   r   PromptContinueEnableServicer   r]   projectNumberGetIamPolicyr\   HttpForbiddenError_CurrentRolesForAccount#_VerifyCloudBuildStoragePermissionsCLOUD_BUILD_STORAGE_PERMISSIONS_VerifyRolesAndPromptIfMissing	frozensetROLE_EDITOR)
project_id cloudbuild_service_account_rolescompute_service_account_roles!custom_cloudbuild_service_accountcustom_compute_service_accountprojectexpected_servicesservice_nameprompt_messageenable_servicebuild_accountcompute_accountpolicy current_cloudbuild_account_rolescurrent_compute_account_roless                  rC   _CheckIamPermissionsr     s   $ Z('1'l(():):LII128&2F  "00

2"$n 
""7#4#4lCJ VL!		# (& FLL-&(//)M
 AGG


!  $*11&(O	&&z2F &=&" &&%	 !&01	 #:# 55"%B%' 6G 
	/	/ KK	 F=*K	L s   )F :GGc                 `    [        X#5      nU(       d  g[        n[	        U5       Vs/ s H  nSR                  Xa5      PM     nnSR                  SR                  U5      5      n[        R                  " USR                  U5      SS9n	U	(       d  g[        R                  " SR                  X5      5         [        R                  " XU5        g! [        R                   a    Un Nf = fs  snf ! [        R                   a(    [        R                  " S	R                  X5      5         gf = f)
a0  Check for IAM permissions for an account and prompt to add if missing.

Args:
  project_id: A string with the id of the project.
  account: A string with the identifier of an account.
  applied_roles: A set of strings containing the current roles for the
    account.
  required_storage_permissions: A set of strings containing the required
    storage permissions for the account. If a permissions isn't found, then
    the user is prompted to add these permissions in a custom role manually or
    accept adding the storage administrator role automatically.
N{0} {1}CThe following IAM permissions are needed for this operation:
[{0}]

zYou can add the cloud build service account to a custom role with these permissions or to the predefined role: {0}. Would you like to add it to {0}Tmessageprompt_stringr   Adding [{0}] to [{1}]Your account does not have permission to add roles to the service account {0}. If import fails, ensure "{0}" has the roles "{1}" before retrying.)_FindMissingStoragePermissionsr\   r   ROLE_STORAGE_ADMINsortedr^   joinr   r   r   infor   AddIamPolicyBindingr]   )
r   accountapplied_rolesrequired_storage_permissionsmissing_storage_permissionstorage_admin_role
permissionep_tabler   add_storage_admins
             rC   r   r   t  s-   $>!?" 
$
) 9::* z+:  
tyy*+  !//!6"45 

(("))'FG
$$Z:LM= 
	/	/ >!=>. 
	/	/ KK	<<BF=
 s(   C C,8C1 C)(C)19D-,D-c                 6   [         R                  " SS5      n[        5       n[        U 5       Hf  nUR	                  US9n[        [         R
                  " SS5      R                  R                  U5      R                  5      nUR                  U5      nMh     X-
  $ )ai  Check which required storage permissions were not covered by given permissions.

Args:
  applied_roles: A set of strings containing the current roles for the
    account.
  required_storage_permissions: A set of strings containing the required cloud
    storage permissions for the account.

Returns:
  A set of missing storage permissions that is not covered.
iamv1name)
r   GetMessagesModulesetr   IamRolesGetRequestGetClientInstancerolesr   includedPermissionsunion)r   r   iam_messagesapplied_permissionsapplied_rolerequestapplied_role_permissionss          rC   r   r     s     ''t4,]+l--<-@G"ud+	ss7|		 
 .334LM , 
&	;;rF   c                 `    [        X#5      nU(       d  g[        U5       Vs/ s H  nSR	                  XQ5      PM     nnSR	                  SR                  U5      5      n[        R                  " USSS9nU(       d  g[        U5       H@  n[        R                  " SR	                  X5      5         [        R                  " XU5        MB     g! [        R                   a    X2-
  n Nf = fs  snf ! [        R                   a)    [        R                  " S	R	                  X5      5           gf = f)
a  Check for IAM permissions for an account and prompt to add if missing.

Args:
  project_id: A string with the id of the project.
  account: A string with the identifier of an account.
  applied_roles: A set of strings containing the current roles for the
    account.
  required_roles: A set of strings containing the required roles for the
    account. If a role isn't found, then the user is prompted to add the role.
Nr   r   r   z%Would you like to add the permissionsTr   r   r   )_FindMissingRolesr\   r   r   r^   r   r   r   r   r   r   r   r]   )	r   r   r   required_rolesmissing_rolesroler   r   	add_roless	            rC   r   r     s   3%mDM 

:@:OP:O$it-:O(Ptyy*+  ''; )
 

]#dHH$++G:;&&zDA $% 
	/	/ 3"2M3 Q  11 	kk>>Df?'(
 s(   C C+1C0C('C(09D-,D-c                    UR                  U 5      (       a  g[        R                  " SS5      n0 n[        5       n[        5       n[        5       n[	        U5       Hj  nUR                  US9n[        [        R                  " SS5      R                  R                  U5      R                  5      n	XU'   UR                  U	5      nMl     [	        U 5       Hf  n
UR                  U
S9n[        [        R                  " SS5      R                  R                  U5      R                  5      nUR                  U5      nMh     XE-
  nU H.  nUR                  X7   5      (       d  M  UR                  U5        M0     U$ )a%  Check which required roles were not covered by given roles.

Args:
  applied_roles: A set of strings containing the current roles for the
    account.
  required_roles: A set of strings containing the required roles for the
    account.

Returns:
  A set of missing roles that is not covered.
Nr   r   r   )issubsetr   r   r   r   r   r   r   r   r   r   intersectionadd)r   r   r   required_role_permissionsrequired_permissionsr   unsatisfied_rolesr   r   role_permissionsr   r   unsatisfied_permissionss                rC   r   r     s\    ]++''t4, e^$d--4-8G411tU33w<(;(;=&6d#/556FG % ]+l--<-@G"4#9#9t$U33w<(;(; =-33 "	 , 1Fd++,E,KLLD!  
rF   c                 B   ^ [        U4S jU R                   5       5      $ )zReturns a set containing the roles for `account`.

Args:
  project_iam_policy: The response from GetIamPolicy.
  account: A string with the identifier of an account.
c              3   `   >#    U  H#  nTUR                   ;   d  M  UR                  v   M%     g 7frr   )membersr   ).0bindingr   s     rC   	<genexpr>*_CurrentRolesForAccount.<locals>.<genexpr>/  s*      ,77??* W\\7s   ..)r   bindings)project_iam_policyr   s    `rC   r   r   (  s%     
 ,.77, 
, ,rF   c                    [         R                  " SR                  [        U 5      5      5        UR                  R                  UR                  U [        R                  R                  R                  R                  5       S95      n[        R                  " UR                  5      n[        R                  " UR                   U5      R"                  n[$        R&                  R                  SUR(                  UR*                  S9n[         R,                  " U5        UR.                  (       a;  [         R0                  R3                  SR                  UR.                  5      5        XV4$ [         R0                  R3                  S5        XV4$ )a  Create a build in cloud build.

Args:
  build_config: A cloud build Build message.
  client: The cloud build api client.
  messages: The cloud build api messages module.

Returns:
  Tuple containing a cloud build build object and the resource reference
  for that build.
submitting build: {0})rh   r   zcloudbuild.projects.builds)
collectionr   rw   Logs are available at [{0}].(Logs are available in the Cloud Console.)r   debugr^   reprprojects_buildsCreate%CloudbuildProjectsBuildsCreateRequestr   VALUEScorer   r   r   MessageToJsonmetadataJsonToMessageBuildOperationMetadatarh   r   REGISTRYr   rw   CreatedResourcelogUrlrZ   r=   )build_configclientrU   opjsonrh   re   s          rC   _CreateCloudBuildr   4  s.    ))#**4+=>?$$44
(9(9(>(>(F(F(J(J(L 5 NO" 
			,$

 
 !@!@$
G
M
M%  ''-	 ( )
 i 
\\JJ3::5<<HI 
	 JJ?@		rF   c           	         [         R                  " SR                  [        U 5      5      5        [        R
                  R                  S[        R                  R                  R                  R                  5       US9nUR                  R                  UR                  [        R                  R                  R                  R                  5       UR                  5       U S95      n[         R"                  " UR$                  5      n[         R&                  " UR(                  U5      R*                  n[        R
                  R-                  SSSUR.                  UUR0                  S.S	9n[         R2                  " U5        UR4                  (       a;  [         R6                  R9                  S
R                  UR4                  5      5        Xx4$ [         R6                  R9                  S5        Xx4$ )aA  Create a regional build in Cloud Build.

Args:
  build_config: A cloud build Build message.
  client: The cloud build api client.
  messages: The cloud build api messages module.
  build_region: region to which build in

Returns:
  Tuple containing a cloud build build object and the resource reference
  for that build.
r   zcloudbuild.projects.locations)r   
projectsIdlocationsId)r   parentrh   Nz$cloudbuild.projects.locations.buildsr   )r  r  buildsId)r   api_versionparamsr   r   )r   r   r^   r   r   r   r   r   r   r   r   	GetOrFailprojects_locations_builds.CloudbuildProjectsLocationsBuildsCreateRequestr   RelativeNamer   r   r   r   r   rh   Parser   rw   r   r   rZ   r=   )	r   r   rU   build_regionparent_resourcer   r   rh   re   s	            rC   _CreateRegionalCloudBuildr  V  s    ))#**4+=>?&&--0""''//99; .  /
 ''..==%%**22668 --/| > EF"
 
			,$

 
 !@!@$
G
M
M%   &&
7%hh	 ' 	) i 
\\JJ3::5<<HI 
	 JJ?@		rF   c                 6   [         R                  R                  R                  R	                  5       nUR                  SS5      nUR                  SS5      nSR                  U5      nU (       a  SR                  X@5      R                  5       n[        XA5      nU$ )zDetermine bucket name for daisy.

Args:
  bucket_location: str, specified bucket location.
  add_random_suffix: bool, specifies if a random suffix must be generated.

Returns:
  str, bucket name for daisy.
:-.z{0}-daisy-bktz{0}-{1})	r   r   r   r   r  replacer^   lower_GetSafeBucketName)bucket_locationadd_random_suffixr   safe_projectbucket_namesafe_bucket_names         rC   GetDaisyBucketNamer    s     ""**446'c*,%%c3/,&&|4+"";@FFHK'G	rF   c                 x   ^ [         R                  mSSR                  U4S j[        U S-
  5       5       5      -   $ )zGenerates a random bucket suffix of a predefined length.

Args:
  suffix_len: int, the length of the generated suffix.

Returns:
  str, generated suffix in the format '-xxxxxx...'
r   c              3   P   >#    U  H  n[         R                  " T5      v   M     g 7frr   )randomchoice)r   iletterss     rC   r   ._GenerateRandomBucketSuffix.<locals>.<genexpr>  s     M7L!v}}W--7Ls   #&   )stringascii_lowercaser   range)
suffix_lenr#  s    @rC   _GenerateRandomBucketSuffixr*    s3     ""'	rwwMuZ!^7LMM	MMrF   c                     U R                  SS5      n U(       a  [        5       nUR                  SS5      nOSnU SS R                  SS5      U SS -   n S[        U5      -
  n[        U 5      U:  a  U SU n X-   $ )	zUpdates bucket name to meet https://cloud.google.com/storage/docs/naming.

Args:
  bucket_name: str, input bucket name.
  add_random_suffix: bool, if specified a random suffix is added to its name.

Returns:
  str, safe bucket name.
googlezgo-ogler  N   googzgo-og?   )r  r*  len)r  r  suffixmax_lens       rC   r  r    s     ##Hi8+(*F^^Hi0FF BQ''8;qr?J+ V'hw'K		rF   c                 j   [        U 5      n UR                  UU UUS9  U$ ! [        R                   a    Sn[	        S5       H  n[        U SS9n UR                  UU UUS9  SnUn  Oa! [
        R                   a2  n[        SR                  U[        R                  " U5      S95      eSnAf[        R                   a     M  f = f   U(       d  [        S	R                  U5      5      e U$ [
        R                   a2  n[        SR                  U[        R                  " U5      S95      eSnAff = f)
a|  Creates Daisy bucket in current project.

Args:
  bucket_location: str, specified bucket location.
  storage_client: storage client
  enable_uniform_level_access: bool, to enable uniform bucket level access.
  soft_delete_duration: int, the soft delete duration in seconds.

Returns:
  str, Daisy bucket.

Raises:
  DaisyBucketCreationException: if unable to create Daisy Bucket.
)locationenable_uniform_level_accesssoft_delete_durationF
   T)r  z8Unable to create a temporary bucket [{bucket_name}]: {e})r  ro   NznUnable to create a temporary bucket `{0}` needed for the operation to proceed as it exists in another project.)r  CreateBucketIfNotExistsr   BucketInWrongProjectErrorr(  r\   r   r   r^   http_excHttpException)	r  storage_clientr5  r6  r  "bucket_in_project_created_or_found_randomized_bucket_nameerrs	            rC   CreateDaisyBucketInProjectrA    s   ( #?3++E** $?1	 + V 
K 
	.	.   */&2Y1/DH J.."$(C!5	 	/ 	
 .2*, !** I*FMM'8+A+A#+F N HI 	I 22  * .(86+    . 
	 
	&	& E
&BII#x'='=c'B 	J 	DE EEsK   ! .D2A("D2(C<-B))C D2C&D2-D2 -D--D2c                     [         R                  R                  R                  R	                  5       (       aF  [
        R                  " [         R                  R                  R                  R	                  5       5      $ [         R                  R                  R                  R	                  5       (       a2  [         R                  R                  R                  R	                  5       $ [        S5      e)zGets region from global properties/args that should be used for subnet arg.

Returns:
  str, region
Raises:
  SubnetException: if region couldn't be inferred.
z#Region or zone should be specified.)	r   r   computezoner   r   ZoneNameToRegionNameregionr~   rG   rF   rC   GetSubnetRegionrG  	  s     ##''))%%j&7&7&?&?&D&D&H&H&JKK  ''++--$$++//11=>>rF   c                     A[        US[        R                  5        [        [        U 5      n[        [        UU5      n[        XXU[        [        US9$ )a  Run a build over gce_vm_image_import on Google Cloud Builder.

Args:
  args: An argparse namespace. All the arguments that were provided to this
    command invocation.
  import_args: A list of key-value pairs to pass to importer.
  tags: A list of strings for adding tags to the Argo build.
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  release_track: release track of the command used. One of - "alpha", "beta"
    or "ga"
  docker_image_tag: Specified docker image tag.

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
client_versionr  )
	AppendArgr   CLOUD_SDK_VERSION_GetBuilderRegion_GetImageImportRegion_GetBuilder _IMAGE_IMPORT_BUILDER_EXECUTABLERunImageCloudBuild+IMPORT_ROLES_FOR_CLOUDBUILD_SERVICE_ACCOUNT(IMPORT_ROLES_FOR_COMPUTE_SERVICE_ACCOUNTargsimport_argstagsrg   release_trackdocker_image_tagbuilder_regionbuilders           rC   RunImageImportr\    V    8 K)6+C+CD$%:DA.8:J&('	D;mGD)7
9 9rF   c                 Z    U(       a	  U " U5      nOU " 5       nU[         ;   a	  [         U   nU$ )zReturns a region to run a Cloud build in.

Args:
  region_getter: function that returns a region to run build in
  args: args for region_getter
Returns: Cloud Build region
)GCS_TO_AR_REGIONS)region_getterrU  rF  s      rC   rM  rM  A  s0     
4 F_F  v&F	-rF   c                 N    U(       a  [        XU5      nU(       a  U$ [        U US9$ )a  Returns a path to a builder Docker images.

If a region can be determined from region_getter and if regionalized builder
repos are enabled, a regionalized builder is returned. Otherwise, the default
builder is returned.

Args:
  executable: name of builder executable to run
  docker_image_tag: tag for Docker builder images (e.g. 'release')
  builder_region: region for the builder

Returns:
  str: a path to a builder Docker images.
)
executablerY  )GetRegionalizedBuilderGetDefaultBuilder)rb  rY  rZ  regionalized_builders       rC   rO  rO  S  s3     1*2BD!!	j,<
> >rF   c                     U(       d  g[        U 5      n[        X0X5      nU(       a  U$ U[        :X  a  g[        n[        XPX5      nU(       a  U$ g)a  Return Docker image path for regionalized builder wrapper.

Args:
  executable: name of builder executable to run
  region: GCS region for the builder
  docker_image_tag: tag for Docker builder images (e.g. 'release')

Returns:
  str: path to Docker images for regionalized builder.
r  )GetGcpProjectNameGetRegionalisedBuilderIfExists!_COMPUTE_IMAGE_TOOLS_PROJECT_NAME)rb  rF  rY  gcp_projectre  fallback_project_namefallback_regionalized_builders          rC   rc  rc  k  sb     
 "*-+7v9 55;"@#C #((	rF   c                 T    [         R                  U UUUS9n[        U5      (       a  U$ g)a  Return Docker image path for regionalized builder wrapper if exist.

Args:
  gcp_project: Artifact Registry's GCP project name.
  executable: name of builder executable to run
  region: GCS region for the builder
  docker_image_tag: tag for Docker builder images (e.g. 'release')

Returns:
  str: Docker image path for regionalized builder wrapper if exist, otherwise
    return empty string.
)rj  rb  rF  rY  r  )$_REGIONALIZED_BUILDER_DOCKER_PATTERNr^   IsArtifactRegistryImageExist)rj  rb  rF  rY  re  s        rC   rh  rh    s>     >DD'	 E ) ""677	rF   c                     [        U 5      nSn[        n[        UR                  UU US95      (       a  [        R                  UU US9$ [        R                  UU US9$ )zReturn Docker image path for GCR builder wrapper.

Args:
  executable: name of builder executable to run
  docker_image_tag: tag for Docker builder images (e.g. 'release')

Returns:
  str: path to Docker images for GCR builder.
z<https://gcr.io/v2/{gcp_project}/{executable}/manifests/{tag})rj  rb  tag)rj  rb  rY  )rg  ri  IsGcrImageExistr^   _DEFAULT_BUILDER_DOCKER_PATTERN)rb  rY  rj  gcr_image_get_api_urlrk  s        rC   rd  rd    s     "*-+X;*11
 2    +11) 2 + + 
)	/	/'' 
0 
) )rF   c                 P    [         [        [        [        /nX;  a  [        $ [
        $ )zReturns the GCP project name based on the executable/tool name.

Args:
  executable: name of builder executable to run

Returns:
  str: the GCP project name.
)rP   _IMAGE_EXPORT_BUILDER_EXECUTABLE_OVF_IMPORT_BUILDER_EXECUTABLE(_IMAGE_ONESTEP_IMPORT_BUILDER_EXECUTABLEri  "_COMPUTE_IMAGE_IMPORT_PROJECT_NAME)rb   compute_image_import_executabless     rC   rg  rg    s.     'G&F&D&N&P"
 7,,	++rF   c                 ^     [         R                  " U 5        g! [        [        4 a     gf = f)zChecks if Artifact Registry Image is reachable or not.

Args:
  image_url: The Image URL to check.

Returns:
  True if the AR image is reachable, False otherwise.
TF)r   GetDockerImager	   r   )	image_urls    rC   ro  ro    s/    y)
Y	' s    ,,c                      SS0n[         R                  " 5       R                  U US9nUR                  S:X  a  gg! [        [
        4 a     gf = f)zChecks if a Container Registry Image is reachable or not.

Args:
  image_url: The Image URL to check.

Returns:
  True if the URL is reachable, False otherwise.
zContent-Typezapplication/json)headers   TF)r   
GetSessionheadstatus_coder	   r   )r}  r  responses      rC   rr  rr    sc    
12G""$)) * H s"
Y	' s   7; AAc                 x   [         R                  R                  R                  R	                  5       nU(       a  [
        R                  " U5      $ U R                  (       a/  [        U R                  5      (       d  [        U R                  5      $ U R                  (       a  U R                  R                  5       $ g)ziReturn region to run image import in.

Args:
  args: command args

Returns:
  str: region. Can be empty.
r  )r   r   rC  rD  r   r   rE  source_fileIsLocalFile_GetBucketLocationstorage_locationr  rU  rD  s     rC   rN  rN    s     
			"	"	'	'	+	+	-$	%%d++D,<,< = =d..//  &&((	rF   c                 d    SR                  U R                  S5      SS 5      R                  5       $ )z1Returns the GCP region that the input zone is in.r  N)r   splitr  rD  s    rC   GetRegionFromZoner    s)    	$**S/#2&	'	-	-	//rF   c                 p    A[        [        U 5      n[        [        XV5      n[	        XXU[
        [        US9$ )a  Run a build over gce_onestep_image_import on Cloud Build.

Args:
  args: An argparse namespace. All the arguments that were provided to this
    command invocation.
  import_args: A list of key-value pairs to pass to importer.
  tags: A list of strings for adding tags to the Argo build.
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  release_track: release track of the command used. One of - "alpha", "beta"
    or "ga".
  docker_image_tag: Specified docker image tag.

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
rJ  )rM  rN  rO  rx  rQ  rR  rS  rT  s           rC   RunOnestepImageImportr  #  s@    8 $%:DA.@(:'	D;mGD)7
9 9rF   c                     A[        US[        R                  5        [        [        U 5      n[        [        UU5      n[        XXU[        [        US9$ )a  Run a build over gce_vm_image_export on Google Cloud Builder.

Args:
  args: An argparse namespace. All the arguments that were provided to this
    command invocation.
  export_args: A list of key-value pairs to pass to exporter.
  tags: A list of strings for adding tags to the Argo build.
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  release_track: release track of the command used. One of - "alpha", "beta"
    or "ga"
  docker_image_tag: Specified docker image tag.

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
rI  rJ  )
rK  r   rL  rM  _GetImageExportRegionrO  rv  rQ  +EXPORT_ROLES_FOR_CLOUDBUILD_SERVICE_ACCOUNT(EXPORT_ROLES_FOR_COMPUTE_SERVICE_ACCOUNT)rU  export_argsrW  rg   rX  rY  rZ  r[  s           rC   RunImageExportr  J  r]  rF   c                     [         R                  R                  R                  R	                  5       nU(       a  [
        R                  " U5      $ U R                  (       a  [        U R                  5      $ g)ziReturn region to run image export in.

Args:
  args: command args

Returns:
  str: region. Can be empty.
r  )	r   r   rC  rD  r   r   rE  destination_urir  r  s     rC   r  r  r  sU     
			"	"	'	'	+	+	-$	%%d++d2233	rF   c           
      N   [         R                  " [        R                  R                  R
                  R                  5       5      n[        U[        U5      [        U5      SU ;   a  U R                  OSSU ;   a  U R                  OS5        [        XUS/U-   X@R                  US9$ )av  Run a build related to image on Google Cloud Builder.

Args:
  args: An argparse namespace. All the arguments that were provided to this
    command invocation.
  builder: A path to builder image.
  builder_args: A list of key-value pairs to pass to builder.
  tags: A list of strings for adding tags to the Argo build.
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  cloudbuild_service_account_roles: roles required for cloudbuild service
    account.
  compute_service_account_roles: roles required for compute service account.
  build_region: Region to run Cloud Build in.

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
cloudbuild_service_accountr  compute_service_account	gce-daisyrJ  )projects_utilParseProjectr   r   r   r   r  r   r   r  r  _RunCloudBuildlog_location)	rU  r[  builder_argsrW  rg   r   r   r  r   s	            rC   rQ  rQ    s    6 ))$$..02* 01-.	%	- %%&?4&Gd""R 
|$,m=N=N%1
3 3rF   c                     [        U R                  S-  5      n[        [        US5      S5      nU R                  U-
  n[        SU5      nU$ )NgQ?   ,  r%  )inttimeoutminmax)rU  timeout_offsetdaisy_timeouts      rC   GetDaisyTimeoutr    sL     t||d*+.s>2.4.,,/- a'-	rF   c                      [         $ rr   )_DEFAULT_BUILDER_VERSIONrG   rF   rC   GetDefaultBuilderVersionr    s    	!!rF   c                     g)Nr%  rG   elapseds    rC   <lambda>r    s    1rF   c                    [         R                  " 5       n[         R                  " 5       n	U	R                  U	R	                  U[        U5      S9/USR                  U R                  5      S9n
U(       a  [        R                  R                  U R                  5      n[        US5      (       a,  SR                  UR                  UR                  5      U
l        O SR                  UR                  5      U
l        [        U S5      (       a  U R                   (       ay  U
R                  (       d  ["        R$                  " SS	5      eS
R                  [&        R(                  R*                  R,                  R/                  5       U R                   5      U
l        U(       a  U[2        ;   a	  [2        U   nU(       a  U[4        ;   a  [7        XU	U5      u  pO[9        XU	5      u  pU R:                  (       a  U$ [<        R>                  " [<        R@                  " XU5      5      n[B        RD                  " U5         [G        X5      RI                  XUS9nSSS5        URJ                  U	R                  RL                  RN                  :X  a  [P        RJ                  RS                  S5        URJ                  U	R                  RL                  RT                  :w  a  [W        U5      eU$ ! , (       d  f       N= f)au  Run a build with a specific builder on Google Cloud Builder.

Args:
  args: an argparse namespace. All the arguments that were provided to this
    command invocation.
  builder: A paths to builder Docker image.
  build_args: args to be sent to builder
  build_tags: tags to be attached to the build
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  log_location: GCS path to directory where logs will be stored.
  backoff: A function that takes the current elapsed time and returns
    the next sleep length. Both are in seconds.
  build_region: Region to run Cloud Build in.

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
)r   rU  z{0}s)stepsrW  r  objectgs://{0}/{1}zgs://{0}r  --log-locationzJLog Location  is required when service account is provided for cloud buildz projects/{0}/serviceAccounts/{1})rg   NzXYour build timed out. Use the [--timeout=DURATION] flag to change the timeout threshold.),r
   r   r   rV   	BuildStepr   r^   r  r   r   r  r  hasattrbucketr  
logsBucketr  calliope_exceptionsRequiredArgumentExceptionr   r   r   r   r   serviceAccountAR_TO_CLOUD_BUILD_REGIONSCLOUD_BUILD_REGIONSr  r   async_r   MashHandlerGetCancelBuildHandlerr   CtrlCSectionrO   rp   rZ   rW   TIMEOUTr   r=   SUCCESSrt   )rU  r[  
build_args
build_tagsrg   r  rf   r  r   rU   r   gcs_log_refrh   re   mash_handlers                  rC   r  r    sp   > ,,.&..0( 


*%   mmDLL)   	, $$**4+<+<=K{H%%!/!6!6{7I7I7B7I7I"Kl !+ 1 1+2D2D El d011

)
)""99
 
 #E"K"K&&**,''#L
 l&??,\:L l&990x1=?E9 )xHE 
[[L&&%%f	BD, ##L1)&;LL- M 9E 2 \\X^^99AAAJJ	!" \\X^^99AAA
u
%%	, 21s   2K
K*c                 <   [         R                  " [        R                  R                  R
                  R                  5       5      n[        U[        [        5      [        [        5      UU5        / n [        U SU5        [        U SS5        [        U SU5        [        U SU5        [        U SU5        [        U SU5        [        U SU5        U(       aP  [        U S	S
R                  UR                  5        V!V"s/ s H  u  n!n"SR                  U!U"5      PM     sn"n!5      5        [        U SU	5        [        U SU
5        [        U SU5        [        U SU5        [        U SU5        [        U SU5        U(       a  [        U SU5        U(       a  [        U SU5        [        U SU5        U(       a  [        U SS
R                  U5      5        [        U SU5        [        U S[!        U 5      S5        [        U SU5        [#        U XR$                  5        U(       a  [        U SU5        [        U SU5        [        U S[&        R(                  5        [        U SU5        U(       a  [        U SU5        U(       a  [        U SU5        OU(       a  [        U SS S!S"9  U(       a  [        U S#S
R                  U5      5        OU(       a  [        U S#S S!S"9  S$S%/n#S& n$[+        [,        5      n%[/        [0        U R2                  U%5      n&[5        U U&U U#UU$U R6                  U%S'9$ s  sn"n!f )(a&  Run a OVF into VM instance import build on Google Cloud Build.

Args:
  args: an argparse namespace. All the arguments that were provided to this
    command invocation.
  compute_client: Google Compute Engine client.
  instance_name: Name of the instance to be imported.
  source_uri: A GCS path to OVA or OVF package.
  no_guest_environment: If set to True, Google Guest Environment won't be
    installed on the boot disk of the VM.
  can_ip_forward: If set to True, allows the instances to send and receive
    packets with non-matching destination or source IP addresses.
  deletion_protection: Enables deletion protection for the instance.
  description: Specifies a textual description of the instances.
  labels: List of label KEY=VALUE pairs to add to the instance.
  machine_type: Specifies the machine type used for the instances.
  network: Specifies the network that the instances will be part of.
  network_tier: Specifies the network tier of the interface. NETWORK_TIER must
    be one of: PREMIUM, STANDARD.
  subnet: Specifies the subnet that the instances will be part of.
  private_network_ip: Specifies the RFC1918 IP to assign to the instance.
  no_restart_on_failure: The instances will NOT be restarted if they are
    terminated by Compute Engine.
  os: Specifies the OS of the boot disk being imported.
  tags: A list of strings for adding tags to the Argo build.
  zone: The GCP zone to tell Daisy to do work in. If unspecified, defaults to
    wherever the Argo runner happens to be.
  project: The Google Cloud Platform project name to use for OVF import.
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  release_track: release track of the command used. One of - "alpha", "beta"
    or "ga"
  hostname: hostname of the instance to be imported
  no_address: Specifies that no external IP address will be assigned to the
    instances.
  byol: Specifies that you want to import an image with an existing license.
  compute_service_account: Compute service account to be used for worker
    instances.
  cloudbuild_service_account: CloudBuild service account to be used for
    running cloud builds.
  service_account: Service account to be assigned to the VM instance or
    machine image.
  no_service_account: No service account is assigned to the VM instance or
    machine image.
  scopes: Access scopes to be assigned to the VM instance or machine image
  no_scopes: No access scopes are assigned to the VM instance or machine
    image.
  uefi_compatible: Specifies that the instance should be booted from UEFI.

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
zinstance-names	client-idgcloudovf-gcs-pathno-guest-environmentcan-ip-forwardzdeletion-protectiondescriptionlabels,{}={}machine-typenetworknetwork-tiersubnetzprivate-network-ipno-restart-on-failurebyoluefi-compatibleosrW  rD  r  	-{0}={1}sr   release-trackhostnameclient-versionno-external-ipcompute-service-accountservice-accountr  Tallow_emptyscopesr  zgce-ovf-importc                     U S:  a  S$ S$ Nr        rG   r  s    rC   r  +RunInstanceOVFImportBuild.<locals>.<lambda>      2A525rF   rf   r  r  )r  r  r   r   r   r   r  r   r   rR  rS  rK  AppendBoolArgr   itemsr^   r  _AppendNodeAffinityLabelArgsrU   r   rL  rM  _GetInstanceImportRegionrO  rw  rY  r  r  )'rU  compute_clientinstance_name
source_urino_guest_environmentcan_ip_forwarddeletion_protectionr  r  machine_typer  network_tierr  private_network_ipno_restart_on_failurer  rW  rD  r   rg   rX  r  
no_addressr  r  r  service_accountno_service_accountr  	no_scopesuefi_compatibler   ovf_importer_argskvr  rf   rZ  r[  s'                                          rC   RunInstanceOVFImportBuildr  %  s   t ))$$..02* ;<89  /?{H5~z:!#9;OP!#3^D!#8:MN}k:hhHAq!,HIK~|<y'2~|<x035GH!#:%'	#VT2#%6HtR(	$8vt,y/$*?My'20$8O8OP-@z84/1I1IJ!#3Z@!:%'!2OD!2BDI388F+;<24@-.*5'$%=>.68M8M&('	
$$!
# #U Is   9Lc                 (
   [         R                  " [        R                  R                  R
                  R                  5       5      n[        U[        [        5      [        [        5      SU ;   a  U R                  OSSU ;   a  U R                  OS5        SnU R                  (       d"  U R                  (       d  U R                  (       aL  [         R"                  " U R                  U R                  U R                  [%        U SS5      [%        U SS5      S9n/ n['        USU R(                  5        ['        US	U R*                  5        ['        US
S5        ['        USU R,                  5        [/        USU R0                  (       + 5        [/        USU R2                  5        ['        USU R4                  5        U R6                  (       aX  ['        USSR9                  U R6                  R;                  5        VVs/ s H  u  pxSR=                  Xx5      PM     snn5      5        ['        USU5        ['        USU R>                  5        ['        USU R@                  5        ['        USU RB                  5        [/        USU RD                  (       + 5        ['        USU RF                  5        [%        U SS5      =(       d    Sn	URH                  RJ                  RL                  RN                  U	;   n
U
(       a  [/        USS5        SU ;   a  [/        USU RP                  5        U RR                  (       a&  ['        USSR9                  U RR                  5      5        ['        US[        R                  RT                  RV                  RY                  5       5        ['        US [[        U 5      S!5        ['        US"U R
                  5        U(       a  ['        US#U5        ['        US$[\        R^                  5        [/        US%U R`                  5        SU ;   a  ['        US&U R                  5        [%        U S'S5      n[%        U S(S5      nU(       a  ['        US)U5        O[%        U S*S+5      (       a  ['        US)SSS,9  U(       a  ['        US'SR9                  U5      5        O[%        U S-S+5      (       a  ['        US'SSS,9  S.S//nS0 n[c        [d        U 5      n[f        n[i        U S15      (       a  U Rj                  n[m        [n        UU5      n[q        U UUUUUU Rr                  US29$ s  snnf )3a  Run a OVF into VM instance import build on Google Cloud Builder.

Args:
  args: an argparse namespace. All the arguments that were provided to this
    command invocation.
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  release_track: The release track of the command used. One of - "alpha",
    "beta" or "ga".
  messages: The definitions of messages for the machine images import API.

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
r  r  r  Ncustom_extensionscustom_vm_type)r  
custom_cpucustom_memoryextvm_typezmachine-image-namezmachine-image-storage-locationr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  guest_os_featuresrG   r  Tr  rW  rD  r  r  r   r  r  r  r  r  r  r  r  Fr  r   r  zgce-ovf-machine-image-importc                     U S:  a  S$ S$ r  rG   r  s    rC   r  /RunMachineImageOVFImportBuild.<locals>.<lambda>0  r  rF   rY  r  ):r  r  r   r   r   r   r  r   r   rR  rS  r  r  r  r	  r
  r   InterpretMachineTypegetattrrK  IMAGEr  r  r  guest_environmentr  r  r  r   r  r^   r  r  r  restart_on_failurer  GuestOsFeatureTypeValueValuesEnumUEFI_COMPATIBLEr   r  rW  rC  rD  r   r  r   rL  r  rM  _GetMachineImageImportRegionr  r  rY  rO  rw  r  r  )rU  rg   rX  rU   r   r  r  r  r  r  r  r  r  r  rf   rZ  rY  r[  s                     rC   RunMachineImageOVFImportBuildr    sW   ( ))$$..02* ;<89	%	- %%&?4&Gd""R ,	$//T-?-?!66&&??((D-t4.57L 3TZZ@?!!#{H5~t?!#9***,!#3T5H5HI}d.>.>?	[[hh9J9J9LM9Lq,9LMNP~|<y$,,7~t/@/@Ax5!#:+++-tTWW- d$7>D"11AAFF	  #%6=t^#VTYY7	YY$)))<=vz'8'8'@'@'E'E'I'I'KLy/$*?My$,,7-@/1I1IJ!#3T__E$&!:**,44(&D"3T:/!2ODt)511!2BDI388F+;<t[%((24@;<*5'$%A4H.-T%&&,,68H&(' 

$$!
# #w Ns   3Tc                      [         R                  R                  R                  R	                  5       n U (       a  [
        R                  " U 5      $ g)zPReturn region to run instance import in.

Returns:
  str: region. Can be empty.
r  )r   r   rC  rD  r   r   rE  r  s    rC   r  r  E  s;     
			"	"	'	'	+	+	-$	%%d++	rF   c                 D    [         R                  " 5       R                  [        R                  R                  [        U 5      SS9R                  5      nU(       a+  UR                  (       a  UR                  R                  5       $ g! [         R                   a     gf = f)NT)allow_empty_objectr  )r   StorageClient	GetBucketr   ObjectReferenceFromUrl
MakeGcsUrir  r4  r  BucketNotFoundError)gcs_pathr  s     rC   r  r  Q  s    &&(22$$,,x T 	- 	;;A6CF &//__""$$ 
 
	(	( s   BB BBc                     [         R                  R                  R                  R	                  5       nU(       a  [
        R                  " U5      $ U R                  (       a  [        U R                  5      $ g)zqReturn region to run machine image import in.

Args:
  args: command args

Returns:
  str: region. Can be empty.
r  )	r   r   rC  rD  r   r   rE  r  r  r  s     rC   r  r  ]  sQ     
			"	"	'	'	+	+	-$	%%d++doo..	rF   c           
      L   A[         R                  " [        R                  R                  R
                  R                  5       5      n[        U[        [        5      [        [        5      5        [        U R                  S-  5      nU R                  [        US5      -
  n/ n[        USU5        [        USU R                  5        [        USU R                   5        [        USUS5        [        USS	5        U R"                  (       d  [        US
S5        [%        USU R&                  5        [%        USU R(                  5        [        US[*        R,                  5        S/n[/        [0        U 5      n	[3        [4        U R6                  U	5      n
[9        U U
UUUU R:                  U	S9$ )a{  Run a OS Upgrade on Google Cloud Builder.

Args:
  args: an argparse namespace. All the arguments that were provided to this
    command invocation.
  output_filter: A list of strings indicating what lines from the log should
    be output. Only lines that start with one of the strings in output_filter
    will be displayed.
  instance_uri: instance to be upgraded.
  release_track: release track of the command used. One of - "alpha", "beta"
    or "ga"

Returns:
  A build object that either streams the output or is displayed as a
  link to the build.

Raises:
  FailedBuildException: If the build is completed and not 'SUCCESS'.
g{Gz?r  instancez	source-osz	target-osr  r  r  r  zcreate-machine-backupfalsezauto-rollbackzuse-staging-install-mediar  zgce-os-upgraderJ  )r  r  r   r   r   r   r  r   r   /OS_UPGRADE_ROLES_FOR_CLOUDBUILD_SERVICE_ACCOUNT,OS_UPGRADE_ROLES_FOR_COMPUTE_SERVICE_ACCOUNTr  r  r  rK  	source_os	target_oscreate_machine_backupr  auto_rollbackuse_staging_install_mediar   rL  rM  _GetOSUpgradeRegionrO  _OS_UPGRADE_BUILDER_EXECUTABLErY  r  r  )rU  rg   instance_urirX  r   two_percentos_upgrade_timeoutos_upgrade_argsr  rZ  r[  s              rC   RunOsUpgradeBuildr5  n  sq   * ))$$..02* ?@<=? DLL4'(+||c+s&;;/OZ6O[$..9O[$..9OY(:KHO[(3		#	#o6@$2D2DE!<..0O-v/G/GH !*$%8$?.68M8M&('	

!
# #rF   c                 f    U R                   (       a   [        R                  " U R                   5      $ g)zgReturn region to run OS upgrade in.

Args:
  args: command args

Returns:
  str: region. Can be empty.
r  )rD  r   rE  )rU  s    rC   r/  r/    s#     
YY%%dii00	rF   c                 b    U(       d  U(       a!  U R                  UR                  X5      5        g g rr   appendr^   )rU  r   argformat_patternr  s        rC   rK  rK    s#    KKK%%d01 rF   c                     [        XUS5        g )Nz-{0})rK  rU  r   r:  s      rC   r  r    s    DV$rF   c                 T    U(       d!  U R                  SR                  X5      5        g g )N-{0}={1}r8  r=  s      rC   AppendBoolArgDefaultTruer@    s!    	KK
!!$,- 
rF   c           	          U R                  SSS9  U R                  S[        R                  " SS9SSR                  X5      S	9  [        R
                  R                  U 5        g
)z"Common arguments for Daisy builds.r  zDirectory in Cloud Storage to hold build logs. If not set, ```gs://<project num>.cloudbuild-logs.googleusercontent.com/``` is created and used.helpz	--timeout24h)upper_bound2ha)            Maximum time {} can last before it fails as "TIMEOUT". For example, if
          you specify `2h`, the process fails after 2 hours.
          See $ gcloud topic datetimes for information about duration formats.

          This timeout option has a maximum value of 24 hours.{}
          )typedefaultrC  N)add_argumentr   Durationr^   r   
ASYNC_FLAGAddToParser)parser	operationextra_timeout_helps      rC   AddCommonDaisyArgsrP    sm     	   	E2 vi4  
6 //f%rF   c                 0    U R                  S[        SSS9  g)z(Extra common arguments for Daisy builds.z--docker-image-tagTa
            Specify which docker image tag (of tools from compute-image-tools)
          should be used for this command. By default it's "release", while
          "latest" is supported as well. There may be more versions supported in
          the future.
          )rH  hiddenrC  N)rI  r  rM  s    rC   AddExtraCommonDaisyArgsrT    s%     	&	  
rF   c                 &    U R                  SSSS9  g)zAdds OVF Source URI arg.z--source-uriTzCloud Storage path to one of:
  OVF descriptor
  OVA file
  Directory with OVF package.
For more information about Cloud Storage URIs, see
https://cloud.google.com/storage/docs/request-endpoints#json-api.requiredrC  NrI  rS  s    rC   AddOVFSourceUriArgrY    s"    N	  PrF   c                 F    U R                  SSSSR                  U5      S9  g)z"Adds Google Guest environment arg.z--guest-environment
store_trueTz2The guest environment will be installed on the {}.)actionrH  rC  N)rI  r^   )rM  resources     rC   AddGuestEnvironmentArgr^    s/    ?FF
	  rF   c                 L   U R                  SSSS9  U R                  SSSS9  U R                  SSSS9  U R                  S	SS
S9  U R                  SSS9nUR                  SS9nUR                  SSSS9  UR                  SSSS9  UR                  SS9nUR                  SSS9  g)z$Adds args for image import from AWS.z--aws-access-key-idTz          Access key ID for a temporary AWS credential.
          This ID must be generated using the AWS Security Token Service.
          rV  z--aws-secret-access-keyz          Secret access key for a temporary AWS credential.
          This key must be generated using the AWS Security Token Service.
          z--aws-session-tokenz          Session token for a temporary AWS credential. This session
          token must be generated using the AWS Security Token Service.
          z--aws-regionz0AWS region of the image that you want to import.zI          Specify whether to import from an AMI or disk image.
          z<      If importing an AMI,  specify the following two flags:rB  z--aws-ami-idz"AWS AMI ID of the image to import.z--aws-ami-export-locationz          An AWS S3 bucket location where the converted image file can be
          temporarily exported to before the import to Cloud Storage.z8      If importing a disk image,  specify the following:z--aws-source-ami-file-pathzc          S3 resource path of the exported image file that you want
          to import.
          N)rI  add_mutually_exclusive_group	add_group)	aws_groupstep_to_beginbegin_from_exportbegin_from_files       rC   AddAWSImageImportSourceArgsrf  	  s.             =   88 9 - $-- 4@- A  / ! 
   !I !  "++ 2<+ =/"  rF   c                     U R                   (       a%  [        USU R                   R                  5       5        U R                  (       a&  [        USU R                  R                  5       5        gg)zExtracts network/subnet out of CLI args and append for importer.

Args:
  args: list of str, CLI args that might contain network/subnet args.
  builder_args: list of str, args for builder.
r  r  N)r  rK  r  r  )rU  r  s     rC   AppendNetworkAndSubnetArgsrh  K  sI     
[[lHdkk&7&7&9:	\\lIt||'9'9';< rF   c                 &    U R                  SSSS9  g)zAdds byol arg.z--byolr[  av       Specifies that you want to import an image with an existing license.
     Importing an image with an existing license is known as bring your
     own license (BYOL).

     `--byol` can be specified in any of the following ways:

        + `--byol --os=rhel-8`: imports a RHEL 8 image with an existing license.
        + `--os=rhel-8-byol`: imports a RHEL 8 image with an existing license.
        + `--byol`: detects the OS contained on the disk, and imports
           the image with an existing license.

     For more information about BYOL, see:
     https://cloud.google.com/compute/docs/nodes/bringing-your-own-licensesr\  rC  NrX  rS  s    rC   
AddByolArgrk  Y  s"    O  PrF   c                 z    SR                  US9nU(       a  USR                  U5      -   nU R                  SSUS9  g)zAdds no address arg.a2             Temporary VMs are created in your project during {operation}. Set
           this flag so that these temporary VMs are not assigned external IP
           addresses.

           Note: The {operation} process requires package managers to be
           installed on the operating system for the virtual disk. These package
           managers might need to make requests to package repositories that are
           outside Google Cloud. To allow access for these updates, you need to
           configure Cloud NAT and Private Google Access.
           )rN  z For more information, see {}.z--no-addressr[  rj  N)r^   rI  )rM  rN  docs_url	help_texts       rC   AddNoAddressArgro  n  sJ    
 v	v*  <CCHMMIn\	JrF   c                     SnUS-  nU H  nUSU-   S-   -  nM     U R                  SUR                  XR                  5       S9S9  g)z!Adds Compute service account arg.a,          A temporary virtual machine instance is created in your project during
        {operation}.  {operation_capitalized} tooling on this temporary instance
        must be authenticated.

        A Compute Engine service account is an identity attached to an instance.
        Its access tokens can be accessed through the instance metadata server
        and can be used to authenticate {operation} tooling on the instance.

        To set this option,  specify the email address corresponding to the
        required Compute Engine service account. If not provided, the
        {operation} on the temporary instance uses the project's default Compute
        Engine service account.

        At a minimum, you need to grant the following roles to the
        specified Cloud Build service account:
        r   
        * z--compute-service-accountrN  operation_capitalizedrB  NrI  r^   
capitalizerM  rN  r   help_text_patternr   s        rC   AddComputeServiceAccountArgrx    sn    " td,t33  	!##5I5I5K $ M  rF   c                     SnUS-  nU H  nUSU-   S-   -  nM     U R                  SUR                  XR                  5       S9S9  g)z%Adds Cloud Build service account arg.a          Image import and export tools use Cloud Build to import and export images
        to and from your project.
        Cloud Build uses a specific service account to execute builds on your
        behalf.
        The Cloud Build service account generates an access token for other service
        accounts and it is also used for authentication when building the artifacts
        for the image import tool.

        Use this flag to to specify a user-managed service account for
        image import and export. If you don't specify this flag, Cloud Build
        runs using your project's default Cloud Build service account.
        To set this option, specify the email address of the desired
        user-managed service account.
        Note: You must specify the `--logs-location` flag when
        you set a user-managed service account.

        At minimum, the specified user-managed service account needs to have
        the following roles assigned:
        r   rq  z--cloudbuild-service-accountrr  rB  Nrt  rv  s        rC   AddCloudBuildServiceAccountArgrz    sm    ( td,t33  	$##5I5I5K $   rF   c                 n    [         R                  " X5      nU H  n[        U S[        U5      5        M     g )Nznode-affinity-label)sole_tenancy_util%GetSchedulingNodeAffinityListFromArgsrK  &_BuildOvfImporterNodeAffinityFlagValue)r  rU  compute_client_messagesnode_affinitiesnode_affinitys        rC   r  r    s6    %KK
%/&m!64]CE 'rF   c                     U R                   S-   [        R                  " U R                  5      -   nU R                   H  nUSU-   -  nM     U$ )Nr  )keysix	text_typeoperatorvalues)r  node_affinity_flagvalues      rC   r~  r~    sQ    $((3.2 ##e#+% $	rF   c                     [         R                  R                  U 5      n[        US5      (       a&  SR	                  UR
                  UR                  5      $ SR	                  UR
                  5      $ )zCreates Google Cloud Storage URI for an object or a path.

Args:
  uri: a string to a Google Cloud Storage object or a path. Can be a gs:// or
       an https:// variant.

Returns:
  Google Cloud Storage URI for an object or a path.
r  r  z	gs://{0}/)r   r   r  r  r^   r  r  uriobj_refs     rC   r!  r!    sW     $$S)'Wh  @@gnn--rF   c                     [         R                  R                  U 5      n[        US5      (       a&  SR	                  UR
                  UR                  5      $ [        R                  " U S5      e)a  Creates Google Cloud Storage URI for an object.

Raises storage_util.InvalidObjectNameError if a path contains only bucket
name.

Args:
  uri: a string to a Google Cloud Storage object. Can be a gs:// or
       an https:// variant.

Returns:
  Google Cloud Storage URI for an object.
r  r  zMissing object name)	r   r   r  r  r^   r  r  r   InvalidObjectNameErrorr  s     rC   MakeGcsObjectUrir    sV     $$S)'Wh  @@

-
-c3H
IIrF   c                    U R                   (       d  gUR                  R                  SUR                  R	                  [
        R                  R                  R                  R                  5       U R                   S94/n UR                  U5        g! [        R                   a"    [        R                  " SU R                   5      ef = f)zValidate Compute Engine zone from args.zone.

If not present in args, returns early.
Args:
  args: CLI args dictionary
  compute_client: Compute Client

Raises:
  InvalidArgumentException: when args.zone is an invalid GCE zone
Nr   )r   rD  z--zone)rD  apitools_clientzonesrU   ComputeZonesGetRequestr   r   r   r   r  MakeRequestsr  ToolExceptionInvalidArgumentException)rU  r  zone_requestss      rC   ValidateZoner    s     

"2288%"++BB * 1 1 6 6 > > H H J!YY C () *-L.		*	* L

6
6x
KKLs    B 6Cc                     U R                  5       R                  S5      =(       d    U R                  5       R                  S5      (       + $ )Nzgs://zhttps://)r  r;   )	file_names    rC   r  r    s;    oo**73 7oo**:6
8 8rF   )r  r  )NF)	   )F)NNrr   )r?  F)T)za buildr  )r&  )r  )rL   
__future__r   r   r   r   r&  rb   apitools.base.pyr   r   r\   apitools.base.py.exceptionsr   r	   !googlecloudsdk.api_lib.cloudbuildr
   r   cb_logs+googlecloudsdk.api_lib.cloudresourcemanagerr   googlecloudsdk.api_lib.computer   r   googlecloudsdk.api_lib.servicesr   r   googlecloudsdk.api_lib.storager   r   googlecloudsdk.api_lib.utilr   r:  googlecloudsdk.callioper   r   r  $googlecloudsdk.command_lib.artifactsr   %googlecloudsdk.command_lib.cloudbuildr   /googlecloudsdk.command_lib.compute.sole_tenancyr   r|  #googlecloudsdk.command_lib.projectsr  googlecloudsdk.corer   r   r   r   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr_   r  rs  rn  ry  ri  rP  rv  rw  r0  rx  r  ROLE_COMPUTE_STORAGE_ADMINROLE_STORAGE_OBJECT_VIEWERROLE_STORAGE_OBJECT_ADMINROLE_COMPUTE_ADMINROLE_IAM_SERVICE_ACCOUNT_USER&ROLE_IAM_SERVICE_ACCOUNT_TOKEN_CREATORr   r   r   r   rS  r  r)  rR  r  r(  r  r_  r  GCSLogTailerr6   CloudBuildClientrO   Errorrt   r~   r   r  r   r   r   r   r   r   r   r   r  r  r*  r  rA  rG  r\  rM  rO  rc  rh  rd  rg  ro  rr  rN  r  r  r  r  rQ  r  r  r  r  r  r  r  r  r5  r/  rK  r  r@  rP  rT  rY  r^  rf  rh  rk  ro  rx  rz  r  r~  r!  r  r  r  rG   rF   rC   <module>r     sl   F &  '    % > 1 9 = = D 9 0 F 6 7 , > / ( E < ; U E & * / # * ( ) 2 > 
"X 'w $%; "$9 !#8  #8  !1 !6 +E ($ 9 9 7 *  > )O &* "+ - #  , ( , ( 0 , *!/ + *!/ + *!3 / ,     ,,  DG$<$< DN1:++ 1-j&& -5:#3#3 5V  ')#%b'J=@<6+\(V	,D+\*NB !%	AH?* %=%9P$>0+\4)<,( ,&0 ,D$9X %=%9P( %)*3Z	" #!% $, $bJa#Hy#x		"=#@2
%.
&0 	P?D=P*K&<DE."J(L08rF   