
    C                        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!r!\RD                  S:  a  SSKJ#r#  S r$S r%S r&S r'S r(S r)                 S-S jr*S r+S r,S.S  jr- S/S! jr.S" r/S# r0S$ r1S% r2S& r3S' r4S.S( jr5               S0S) jr6S* r7S+ r8S1S, jr9g)2z)Support library for managing deployments.    )absolute_import)division)unicode_literalsN)encoding)
exceptions)extra_types)configmanager_util)storage_api)storage_util)deterministic_snapshot)errors)staging_bucket_util)log)requests)	resources)resource_transform)files)times      )tfvars_parserc                 B   [         R                  " XS9n[        R                  " UR                  5      n[
        R                  R                  SR                  [        UR                  5      US95        UR                  5        H  n[        R                  R                  UR                  UR                  5      nSR                  UR                   UR"                  UR                  5      n[$        R&                  R)                  USS9nU R+                  Xx5        M     g)a  Uploads a local directory to GCS.

Uploads one file at a time rather than tarballing/zipping for compatibility
with the back-end.

Args:
  gcs_client: a storage_api.StorageClient instance for interacting with GCS.
  source: string, a path to a local directory.
  gcs_source_staging: resources.Resource, the bucket to upload to. This must
    already exist.
  ignore_file: optional string, a path to a gcloudignore file.
)ignore_filez/Uploading {num_files} file(s) totalling {size}.)	num_filessizezgs://{0}/{1}/{2}storage.objects
collectionN)r   DeterministicSnapshotr   TransformSizeuncompressed_sizer   statusPrintformatlenr   GetSortedFilesospathjoinrootbucketobjectr   REGISTRYParseCopyFileToGCS)	
gcs_clientsourcegcs_source_stagingr   source_snapshotsize_strfile_metadatafull_local_pathtarget_obj_refs	            ;lib/googlecloudsdk/command_lib/infra_manager/deploy_util.py_UploadSourceDirToGCSr:   1   s     +@@/  --o.O.OP(**7>>--.X ?  '557mggll=#5#5}7I7IJO'..!!#5#<#<m>P>PN ''--#4 . N _= 8    c                 z   [         R                  " 5       nUc  Sn[        R                  " X#5      nO$SnSR	                  U[        R
                  UU5      n[        R                  R                  USS9n UR                  UR                  US9  S	R	                  [        R                  " [        R                   " 5       5      ["        R$                  " 5       R&                  S
9n	UR(                  (       a  UR(                  S-   U	-   n	[        R                  R+                  SUR                  U	S9n
[,        R.                  R1                  U 5      (       d%  [        R2                  " SR	                  U 5      5      e[,        R.                  R5                  U 5      (       d%  [        R2                  " SR	                  U 5      5      e[7        XPX5        SR	                  U
R                  U
R(                  5      nU$ ! [         R                   a1    [        R                  " SSR	                  UR                  5      5      ef = f)a8  Uploads local content to GCS.

This will ensure that the source and destination exist before triggering the
upload.

Args:
  source: string, a local path.
  stage_bucket: optional string. When not provided, the default staging bucket
    will be used (see GetDefaultStagingBucket). This string is of the format
    "gs://bucket-name/". An "im_source_staging" object will be created under
    this bucket, and any uploaded artifacts will be stored there.
  deployment_short_name: short name of the deployment.
  location: location of the deployment.
  ignore_file: string, a path to a gcloudignore file.

Returns:
  A string in the format "gs://path/to/resulting/upload".

Raises:
  RequiredArgumentException: if stage-bucket is owned by another project.
  BadFileException: if the source doesn't exist or isn't a directory.
TFz{0}{1}/{2}/{3}r   r   )check_ownershipzstage-bucketzlA bucket with name {} already exists and is owned by another project. Specify a bucket using --stage-bucket.z{stamp}-{uuid})stampuuid/)r   r,   r-   zcould not find source [{}]zsource is not a directory [{}]gs://{0}/{1})r
   StorageClientr   DefaultGCSStagingDirr%   STAGING_DIRr   r.   r/   CreateBucketIfNotExistsr,   BucketInWrongProjectErrorc_exceptionsRequiredArgumentExceptionr   GetTimeStampFromDateTimeNowr?   uuid4hexr-   Creater(   r)   existsBadFileExceptionisdirr:   )r2   stage_bucketdeployment_short_namelocationr   r1   used_default_bucket_namegcs_source_staging_dirgcs_source_staging_dir_refstaged_objectr3   upload_buckets               r9   _UploadSourceToGCSrY   W   s   2 ((**#0EE  %-44''	  )1177):  8  
&&"))0 '  #))**599;7::< * -
  &&.55;mKM ))00"'.. 1  
		

'
'$++F3  
v		

'
'(//7  
,>L ''!3!:!:- 
Q 
	.	. 

0
0	 &!;!B!BC	 s   5G5 5AH:c                     SUl         U$ )zIUpdateDeploymentDeleteRequestWithForce adds force flag to delete request.T)force)
unused_refunused_argsrequests      r9   &UpdateDeploymentDeleteRequestWithForcer_      s     '-	.r;   c                 X   U R                   b  gU R                  b  [        R                  " U R                  5      nUS   nUR	                  S5      S   nUR	                  S5      S   n[
        R                  " XE5      n[        R                  " 5       n[
        R                  " Xv5        U $ )zmDeploymentDeleteCleanupStagedObjects deletes staging gcs objects created as part of deployment apply command.Ntargetr@      r   )
errormetadatar   MessageToPyValuesplitr   rC   r
   rB   DeleteStagingGCSFolder)responser]   mdentity_full_name	entity_idrS   staging_gcs_directoryr1   s           r9   DeleteCleanupStagedObjectsrm      s     ^^
"		"	"8#4#4	5B(| &&s+A.I%%c*1-H/DD **,J.. 
/r;   c                     U R                  US9nUb  X|l        U$ Ub  Ub  [        XEXU5      nXl        U$ Ub  Ub  [        XEX#U5      nXl        U$ U R                  UU	U
S9Ul        U$ )a  Returns the TerraformBlueprint message.

Args:
  messages: ModuleType, the messages module that lets us form Config API
    messages based on our protos.
  deployment_short_name: short name of the deployment.
  preview_short_name: short name of the preview.
  location: location of the deployment.
  local_source: Local storage path where config files are stored.
  stage_bucket: optional string. Destination for storing local config files
    specified by local source flag. e.g. "gs://bucket-name/".
  ignore_file: optional string, a path to a gcloudignore file.
  gcs_source:  URI of an object in Google Cloud Storage. e.g.
    `gs://{bucket}/{object}`
  git_source_repo: Repository URL.
  git_source_directory: Subdirectory inside the git repository.
  git_source_ref: Git branch or tag.
  input_values: Input variable values for the Terraform blueprint. It only
    accepts (key, value) pairs where value is a scalar value.

Returns:
  A messages.TerraformBlueprint to use with deployment operation.
)inputValues)repo	directoryref)TerraformBlueprint	gcsSourcerY   	GitSource	gitSource)messagesrR   preview_short_namerS   local_sourcerQ   r   
gcs_sourcegit_source_repogit_source_directorygit_source_refinput_valuesterraform_blueprintrX   s                 r9   _CreateTFBlueprintr      s    L !33 4  $.!$ 
# $9$E&$9[M %2! 
 $6$B&$6+M %2! 
 %-$6$6& %7 %! 
r;   c                 ^    Uc  gU R                  U R                   R                  U5      S9nU$ )aM  Returns the ProviderConfig message.

Args:
  messages: ModuleType, the messages module that lets us form Config API
    messages based on our protos.
  provider_source: Input to control from where to fetch providers.

Returns:
    A messages.ProviderConfig to use with deployment operation or None if
    provider_source is not set.
N)
sourceType)ProviderConfigSourceTypeValueValuesEnum)rw   provider_sourceprovider_configs      r9   _CreateProviderConfigr     sA     ++((BB
 , /
 
r;   c                 <   [        U R                  5       UU5      u  nn/ nUb  [        R                  " U5       Hi  u  nnUR	                  U R
                  R                  R                  UU R                  [        R                  " [        R                  U5      S9S95        Mk     OUb  [        R                  S:  a  [        R                   " S5      e["        R$                  " U5      n[        R                  " U5       Hi  u  nnUR	                  U R
                  R                  R                  UU R                  [        R                  " [        R                  U5      S9S95        Mk     U R
                  R                  US9n[&        R(                  R+                  USS9nUR-                  5       nUR/                  5       R-                  5       n [0        R2                  " U5      nUb  [9        UUU5        [;        U USUUUUUUUUU5      n [=        U U5      n!U R                  UUUU
U UUUUU!S	9
n"U	b  U	U"l        USL n#Sn$U#(       a  [A        U"U5      n$O[C        U"UUU5      n$[D        RF                  " S
U$RH                  5        U(       ar  [D        RJ                  RM                  SRO                  U#(       a  SOSU5      5        [D        RJ                  RM                  SRO                  U$RH                  5      5        U$$ SRO                  U#(       a  SOS5      n%[0        RP                  " U$U%5      n&U&RR                  U R                  RT                  RV                  :X  a   [        RX                  " U&RZ                  5      eU&$ ! [4        R6                   a    Sn GNf = f)a  Updates the deployment if one exists, otherwise creates a deployment.

Args:
  messages: ModuleType, the messages module that lets us form blueprints API
    messages based on our protos.
  async_: bool, if True, gcloud will return immediately, otherwise it will
    wait on the long-running operation.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".
  service_account: User-specified Service Account (SA) to be used as
    credential to manage resources. e.g.
    `projects/{projectID}/serviceAccounts/{serviceAccount}` The default Cloud
    Build SA will be used initially if this field is not set.
  tf_version_constraint: User-specified Terraform version constraint, for
    example, "=1.3.10".
  local_source: Local storage path where config files are stored.
  stage_bucket: optional string. Destination for storing local config files
    specified by local source flag. e.g. "gs://bucket-name/".
  ignore_file: optional string, a path to a gcloudignore file.
  import_existing_resources: By default, Infrastructure Manager will return a
    failure when Terraform encounters a 409 code (resource conflict error)
    during actuation. If this flag is set to true, Infrastructure Manager will
    instead attempt to automatically import the resource into the Terraform
    state (for supported resource types) and continue actuation.
  artifacts_gcs_bucket: User-defined location of Cloud Build logs and
    artifacts in Google Cloud Storage. e.g. `gs://{bucket}/{folder}` A default
    bucket will be bootstrapped if the field is not set or empty
  worker_pool: The User-specified Worker Pool resource in which the Cloud
    Build job will execute. If this field is unspecified, the default Cloud
    Build worker pool will be used. e.g.
    projects/{project}/locations/{location}/workerPools/{workerPoolId}
  gcs_source:  URI of an object in Google Cloud Storage. e.g.
    `gs://{bucket}/{object}`
  git_source_repo: Repository URL.
  git_source_directory: Subdirectory inside the git repository.
  git_source_ref: Git branch or tag.
  input_values: Input variable values for the Terraform blueprint. It only
    accepts (key, value) pairs where value is a scalar value.
  inputs_file: Accepts .tfvars file.
  labels: User-defined metadata for the deployment.
  quota_validation: Input to control quota checks for resources in terraform'
    configuration files.
  annotations: User-defined annotations for the deployment.
  provider_source: Input to control from where to fetch providers.

Returns:
  The resulting Deployment resource or, in the case that async_ is True, a
    long-running operation.

Raises:
  InvalidArgumentException: If an invalid set of flags is provided (e.g.
    trying to run with --target-git-subdir but without --target-git).
N
inputValuekeyvaluer   zF--inputs-file flag is only supported for python version 3.6 and above.additionalProperties%config.projects.locations.deploymentsr   )
nameserviceAccountimportExistingResources
workerPoolterraformBlueprintlabelsannotationstfVersionConstraintquotaValidationproviderConfigLRO: %s{0} request issued for: [{1}]rM   Update Check operation [{}] for status.z{} the deploymentCreatingUpdating)._GeneratesLabelsAnnotations
Deploymentsix	iteritemsappendrs   InputValuesValueAdditionalPropertyTerraformVariabler   PyValueToMessager   	JsonValuesysversion_infor   InvalidDataErrorr   ParseTFvarFiler   r.   r/   NameParentr	   GetDeploymentapitools_exceptionsHttpNotFoundError!_CleanupGCSStagingObjectsNotInUser   r   artifactsGcsBucket_CreateDeploymentOp_UpdateDeploymentOpr   debugr   r#   r$   r%   WaitForApplyDeploymentOperationstateStateValueValuesEnumFAILEDOperationFailedErrorstateDetail)'rw   async_deployment_full_nameservice_accounttf_version_constraintry   rQ   r   import_existing_resourcesartifacts_gcs_bucketworker_poolrz   r{   r|   r}   r~   inputs_filer   quota_validationr   r   labels_messageannotations_messageadditional_propertiesr   r   tfvar_valuestf_input_valuesdeployment_refdeployment_idrS   existing_deploymenttf_blueprintr   
deploymentis_creating_deploymentopprogress_messageapplied_deployments'                                          r9   Applyr   -  s   Z )DV[)%.% mmL1
U""

%
%
6
6
I
I..%66!++U /  J 	 2 
& ##  !//<LmmL1
U""

%
%
6
6
I
I..%66!++U /  J 	 2 //@@0 A / %%++'N , . !%%'-""$))+(,::;OP $%& $
, *(OD/""$7%%/&$ # * %$8J!.$6"	Z)=	>B	')=v
B ))Irww JJ'...HHm	
 JJ7>>rwwGHI(//*j
 *II

 				1	1	8	89 
%
%&8&D&D
EE	a 
	.	. s   N NNc                     [         R                  R                  USS9nUR                  5       nUR	                  5       n[
        R                  " S5        [        R                  " XUR                  5       5      $ )ar  Initiates and returns a CreateDeployment operation.

Args:
  deployment: A partially filled messages.Deployment. The deployment will be
    filled with other details before the operation is initiated.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".

Returns:
  The CreateDeployment operation.
r   r   zCreating the deployment)
r   r.   r/   r   r   r   infor	   CreateDeploymentRelativeName)r   r   r   location_refr   s        r9   r   r     sq     %%++'N , .  &&(, %%'-(($%		,	,!:!:!<
 r;   c                     [         R                  " S5        Uc  UR                  U l        [        R                  " X5      $ )uN  Initiates and returns an UpdateDeployment operation.

Args:
  deployment: A partially filled messages.Deployment. The deployment will be
    filled with its target (e.g. configController, gitTarget, etc.) before the
    operation is initiated.
  existing_deployment: A messages.Deployment. The existing deployment to
    update.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".
  labels: dictionary of string → string, labels to be associated with the
    deployment.

Returns:
  The UpdateDeployment operation.
z Updating the existing deployment)r   r   r   r	   UpdateDeployment)r   r   r   r   s       r9   r   r     s7    . ((-.
 ^+22J		,	,Z	NNr;   c                    U R                  [        U5      S9n[        R                  R	                  S5        [
        R                  " XA5      nUc  U$ UR                  n[        R                  " [        R                  R                  U5      5       n[        R                  " 5       R                  XgS9  SSS5        [        R                  R	                  SU S35        g! , (       d  f       N2= f)a  Creates a signed uri to upload the state file.

Args:
  messages: ModuleType, the messages module that lets us form Infra Manager
    API messages based on our protos.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".
  lock_id: Lock ID of the lock file to verify person importing owns lock.
  file: file path of the statefile to be uploaded.

Returns:
  A messages.StateFile which contains signed uri to be used to upload a state
  file.
lockIdz2Creating signed uri for ImportStatefile request...N)dataz
Statefile z uploaded successfully.)ImportStatefileRequestintr   r#   r$   r	   ImportStateFile	signedUrir   BinaryFileReaderr(   r)   abspathr   
GetSessionput)rw   r   lock_idfileimport_state_file_request
state_filestate_file_urlstate_file_objs           r9   r   r   ?  s      '==\ >  **GH!11* 
\''.bggood34nB 5 **Zv%<=>	 54s   #C!!
C/c                    U R                  US9n[        R                  R                  S5        [        R
                  " XA5      nUc  U$ [        R                  " 5       R                  UR                  5      nUR                  [        R                  5      (       a  US-  n[        R                  " US-   UR                  5        [        R                  R                  SU S35        g)a	  Creates a signed uri to download the state file.

Args:
  messages: ModuleType, the messages module that lets us form Infra Manager
    API messages based on our protos.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".
  draft: Lock ID of the lock file to verify person importing owns lock.
  file: string, the file name to download statefile to.

Returns:
  A messages.StateFile which contains signed uri to be used to download a
  state file.
)draft'Initiating export state file request...N	statefilez.tfstatezExported statefile ) ExportDeploymentStatefileRequestr   r#   r$   r	   ExportDeploymentStateFiler   r   getr   endswithr(   sepr   WriteBinaryFileContentscontent)rw   r   r   r   $export_deployment_state_file_requestr   state_file_datas          r9   r   r   b  s    & // 0  ' **<=!;;** 
\'')--/ 
]]266KDj 0/2I2IJ**D6* 	r;   c                     U R                  5       n[        R                  R                  S5        [        R
                  " X!5      nU$ )a  Creates a signed uri to download the state file.

Args:
  messages: ModuleType, the messages module that lets us form Infra Manager
    API messages based on our protos.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".

Returns:
  A messages.StateFile which contains signed uri to be used to upload a state
  file.
r   )ExportRevisionStatefileRequestr   r#   r$   r	   ExportRevisionStateFile)rw   r   "export_revision_state_file_requestr   s       r9   r   r     sA     (0'N'N'P$**<=!99(* 
r;   c                 p    [         R                  R                  S5        [        R                  " U 5      nU$ )zExports lock info of the deployment.

Args:
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".

Returns:
  A lock info response.
z!Initiating export lock request...)r   r#   r$   r	   
ExportLock)r   	lock_infos     r9   r  r    s2     **67 ++) 
r;   c                    U R                  5       n[        R                  " X25      n[        R                  R                  USS9nUR                  5       n[        R                  " SUR                  5        U(       ah  [        R                  R                  SR                  U5      5        [        R                  R                  SR                  UR                  5      5        U$ Sn[        R                  " XG5      nUR                  U R                  R                   R"                  :X  a  [$        R&                  " S5      e[)        U5      $ )a  Locks the deployment.

Args:
  messages: ModuleType, the messages module that lets us form Infra Manager
    API messages based on our protos.
  async_: bool, if True, gcloud will return immediately, otherwise it will
    wait on the long-running operation.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".

Returns:
  A lock info resource or, in case async_ is True, a
    long-running operation.
r   r   r   z)Lock deployment request issued for: [{0}]r   zLocking the deploymentz!Lock deployment operation failed.)LockDeploymentRequestr	   LockDeploymentr   r.   r/   r   r   r   r   r#   r$   r%   r   	lockStater   LockStateValueValuesEnumLOCK_FAILEDr   r   r  )	rw   r   r   lock_deployment_requestr   r   r   r   lock_responses	            r9   r  r    s     %::<((" %%++'N , . !%%'-))IrwwJJ3::=I JJ7>>rwwGHI-$DD-
 				5	5	A	AB 
%
%&I
JJ	(	))r;   c                    U R                  [        U5      S9n[        R                  R	                  USS9nUR                  5       n[        R                  " XB5      n[        R                  " SUR                  5        U(       ah  [        R                  R                  SR                  U5      5        [        R                  R                  SR                  UR                  5      5        U$ Sn[        R                  " Xx5      n	U	R                  U R                   R"                  R$                  :X  a  [&        R(                  " S5      eU	$ )	a  Unlocks the deployment.

Args:
  messages: ModuleType, the messages module that lets us form Infra Manager
    API messages based on our protos.
  async_: bool, if True, gcloud will return immediately, otherwise it will
    wait on the long-running operation.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".
  lock_id: Lock ID of the deployment to be unlocked.

Returns:
  A deployment resource or, in case async_ is True, a
    long-running operation.
r   r   r   r   z+Unlock deployment request issued for: [{0}]r   zUnlocking the deploymentz#Unlock deployment operation failed.)UnlockDeploymentRequestr   r   r.   r/   r   r	   UnlockDeploymentr   r   r   r#   r$   r%   r   r  r   r  UNLOCK_FAILEDr   r   )
rw   r   r   r   unlock_deployment_requestr   r   r   r   unlock_responses
             r9   r  r    s    , '>>\ ?  %%++'N , . !%%'-**" ))IrwwJJ5<<]K JJ7>>rwwGHI/&FF/
 				5	5	C	CD 
%
%&K
LL	r;   c                    [         R                  " 5       n[        R                  " X 5      n[        R
                  R                  USS9n[        R                  " UR                  5      n[        5       n UR                  XeR                  5      nU H[  n	SR                  U	R                  R                  S5      SS 5      n
UR!                  SR#                  UR                  U
5      5        M]     U(       d  g [&        R(                  " U5      n[+        UR,                  S SS	9nUS
   nUR.                  b%  UR1                  UR.                  R2                  5        U HP  n[5        UR6                  5      S:X  d  M  UR.                  b%  UR1                  UR.                  R2                  5          O   U H  n[        R8                  " X?5        M     g! [         R$                   a     gf = f)ao  Deletes staging object for all revisions except for last successful revision.

Args:
  location: The location of deployment.
  deployment_full_name: string, the fully qualified name of the deployment,
    e.g. "projects/p/locations/l/deployments/d".
  deployment_id: the short name of the deployment.

Raises:
  NotFoundError: If the bucket or folder does not exist.
r   r   r@   N   rA   c                 ,    [        U R                  5      $ N)GetRevisionNumberr   )xs    r9   <lambda>3_CleanupGCSStagingObjectsNotInUse.<locals>.<lambda>U  s    "3AFF";r;   T)r   reverser   APPLIED)r
   rB   r   rC   r   r.   r/   r   BucketReferencer,   set
ListBucketr-   r*   r   rf   addr%   BucketNotFoundErrorr	   ListRevisionssorted	revisionsr   discardrt   strr   rg   )rS   r   r   r1   gcs_staging_dirgcs_staging_dir_ref
bucket_refstaged_objectsitemsitemitem_dirr   r#  lastest_revisionrevisionobjs                   r9   r   r   -  s    ((**'<</ "**00"3 1  ++,?,F,FG*5.!!*.H.HIE$))//#.r23h


 3 : :H
E 
   ''(<="ll;T)
 q\((4+>>HHI h
8>>i'		$	$	0x::DDE	  c..z? + 
	(	( 
s   5BG G*)G*c                 z    [         R                  R                  U SS9nUR                  5       n[	        USS 5      $ )a7  Returns the revision number from the revision name.

   e.g. - returns 12 for
   projects/p1/locations/l1/deployments/d1/revisions/r-12.

Args:
  revision_full_name: string, the fully qualified name of the revision, e.g.
    "projects/p/locations/l/deployments/d/revisions/r-12".

Returns:
  a revision number.
z/config.projects.locations.deployments.revisionsr      N)r   r.   r/   r   r   )revision_full_namerevision_refrevision_short_names      r9   r  r  h  sI     ##))B * , %))+	 $	%%r;   c                    U R                  5       n[        R                  R                  S5        [        R
                  " X15      nUc  U$ [        R                  " 5       R                  UR                  R                  5      n[        R                  " 5       R                  UR                  R                  5      nUR                  [        R                  5      (       a  US-  n[        R                   " US-   UR"                  5        [        R                   " US-   UR"                  5        [        R                  R                  SU SU S35        g)a  Creates a signed uri to download the preview results.

Args:
  messages: ModuleType, the messages module that lets us form Infra Manager
    API messages based on our protos.
  preview_full_name: string, the fully qualified name of the preview,
    e.g. "projects/p/locations/l/previews/p".]
  file: string, the file name to download results to.
Returns:
  A messages.ExportPreviewResultResponse which contains signed uri to
  download binary and json plan files.
z$Initiating export preview results...Npreviewz.tfplanz.jsonzExported preview artifacts z.tfplan and )ExportPreviewResultRequestr   r#   r$   r	   ExportPreviewResultr   r   r   resultbinarySignedUrijsonSignedUrir   r(   r   r   r   r   )rw   preview_full_namer   export_preview_result_requestpreview_result_respbinary_data	json_datas          r9   r8  r8  }  s    ))+   **9:*>># 
\##%))  00+ !!#''  ..) 
]]266IDi1D1DEw	0A0AB**#D6dV5A 	r;   c                    [        UUU 5      n[        U R                  5       UU5      u  nnU R                  R	                  US9nUbM  [
        R                  R                  USS9nUR                  5       R                  5       nUR                  5       nOP[
        R                  R                  USS9nUR                  5       nSR                  [        R                  " 5       S9n[        U SUUUUU	UUUUU5      n[        U U5      nU R                  UUUUUUS9n [        S	 XU4 5       5      (       a  UU l        Ub  UU l        Ub!   U R                  R%                  U5      U l        Ub  UU l        U
b  U
U l        [3        U X#5      n![4        R6                  " SU!R"                  5        U(       ai  [4        R8                  R;                  SR                  SU5      5        [4        R8                  R;                  SR                  U!R"                  5      5        U!$ SR                  S5      n"[<        R>                  " U!U"5      n#U#R@                  U R                  RB                  RD                  :X  a*  [F        RH                  " U#RJ                  RL                  5      e[4        R8                  R;                  SR                  U#R"                  5      5        U#$ ! [(         a    [*        R,                  " S
S5      ef = f)a	  Creates a preview.

Args:
  messages: ModuleType, the messages module that lets us form blueprints API
    messages based on our protos.
  async_: bool, if True, gcloud will return immediately, otherwise it will
    wait on the long-running operation.
  preview_full_name: string, full path name of the preview. e.g.
    "projects/p/locations/l/previews/preview".
  location_full_name: string, full path name of the location. e.g.
    "projects/p/locations/l".
  deployment: deployment reference for a preview.
  preview_mode: preview mode to be set for a preview.
  service_account: User-specified Service Account (SA) to be used as
    credential to manage resources. e.g.
    `projects/{projectID}/serviceAccounts/{serviceAccount}` The default Cloud
    Build SA will be used initially if this field is not set.
  local_source: Local storage path where config files are stored.
  stage_bucket: optional string. Destination for storing local config files
    specified by local source flag. e.g. "gs://bucket-name/".
  ignore_file: optional string, a path to a gcloudignore file.
  artifacts_gcs_bucket: User-defined location of Cloud Build logs and
    artifacts in Google Cloud Storage. e.g. `gs://{bucket}/{folder}` A default
    bucket will be bootstrapped if the field is not set or empty
  worker_pool: The User-specified Worker Pool resource in which the Cloud
    Build job will execute. If this field is unspecified, the default Cloud
    Build worker pool will be used. e.g.
    projects/{project}/locations/{location}/workerPools/{workerPoolId}
  gcs_source:  URI of an object in Google Cloud Storage. e.g.
    `gs://{bucket}/{object}`
  git_source_repo: Repository URL.
  git_source_directory: Subdirectory inside the git repository.
  git_source_ref: Git branch or tag.
  input_values: Input variable values for the Terraform blueprint. It only
    accepts (key, value) pairs where value is a scalar value.
  inputs_file: Accepts .tfvars file.
  labels: User-defined metadata for the preview.
  annotations: User-defined annotations for the preview.
  provider_source: Input to control where to fetch providers.
  tf_version_constraint: User-specified Terraform version constraint, for
    example, "=1.3.10".

Returns:
  The resulting Preview resource or, in the case that async_ is True, a
    long-running operation.

Raises:
  InvalidArgumentException: If an invalid set of flags is provided (e.g.
    trying to run with --target-git-subdir but without --target-git).
r   N"config.projects.locations.previewsr   zconfig.projects.locationszim-preview-{uuid})r?   )r   r   r   r   r   r   c              3   (   #    U  H  oS Lv   M
     g 7fr   ).0_s     r9   	<genexpr>Create.<locals>.<genexpr>$  s     L K1$ Ks   z--preview-modez>Invalid preview mode. Supported values are DEFAULT and DELETE.r   r   rM   r   z{} the previewr   zCreated preview: {})'_ParseInputValuesAndFiler   Previewrs   r   r   r.   r/   r   r   r%   r?   rK   r   r   anyr   r   PreviewModeValueValuesEnumpreviewMode	TypeErrorrG   UnknownArgumentExceptionr   r   _CreatePreviewOpr   r   r#   r$   r	   WaitForCreatePreviewOperationr   r   r   r   r   errorStatusmessage)$rw   r   r<  location_full_namer   preview_moder   ry   rQ   r   r   r   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   preview_refrS   
preview_idr   r   r   r6  r   r   applied_previews$                                       r9   rM   rM     s   V 3K+(C&+)%.% //@@0 A / "$$**&J + K !!#((*H!!#J%%++'B , L   "H %+++>J#
, *(OD/$%$/  ' 	L? KLLL!-G"$GLL$,,GG
g #G%!5G!2G"))Irww JJ'..j	
 JJ7>>rwwGHI%,, 'DD
/
 				.	.	5	56 
%
%o&A&A&I&I
JJ**(//0D0DEF	W  L11

JL LLs   	 K "K6c                     Uc  [         R                  " U SU5      $ [        R                  R	                  USS9nUR                  5       n[        R                  " S5        [         R                  " XU5      $ )a  Initiates and returns a CreatePreview operation.

Args:
  preview: A partially filled messages.preview. The preview will be filled
    with other details before the operation is initiated.
  preview_full_name: string, the fully qualified name of the preview, e.g.
    "projects/p/locations/l/previews/p".
  location_full_name: string, the fully qualified name of the location, e.g.
    "projects/p/locations/l".

Returns:
  The CreatePreview operation.
NrB  r   zCreating the preview)r	   CreatePreviewr   r.   r/   r   r   r   )r6  r<  rT  rV  rW  s        r9   rP  rP  ]  sv     ++GT;MNN""(($H ) J+!*((!"		)	)-
 r;   c                 N   / nU b  [         R                  " U 5       Hh  u  pEUR                  UR                  R                  R                  UUR                  [        R                  " [        R                  U5      S9S95        Mj     U$ Ub  [        R                  " U5      n[         R                  " U5       Hh  u  pEUR                  UR                  R                  R                  UUR                  [        R                  " [        R                  U5      S9S95        Mj     U$ )a  Parses input file or values and returns a list of additional properties.

Args:
  input_values: Input variable values for the Terraform blueprint. It only
    accepts (key, value) pairs where value is a scalar value.
  inputs_file: Accepts .tfvars file.
  messages: ModuleType, the messages module that lets us form blueprints API
    messages based on our protos.

Returns:
  The additional_properties list.
r   r   )r   r   r   rs   r   r   r   r   r   r   r   r   r   )r~   r   rw   r   r   r   r   s          r9   rI  rI  v  s    mmL1
""

%
%
6
6
I
I..%66!++U /  J 	 20 
  //<LmmL1
""

%
%
6
6
I
I..%66!++U /  J 	 2 
r;   c                 p   0 n0 nUbO  U R                  [        R                  " U5       VVs/ s H  u  pVU R                   R                  XVS9PM      snnS9nUbO  U R	                  [        R                  " U5       VVs/ s H  u  pVU R                  R                  XVS9PM      snnS9nX44$ s  snnf s  snnf )a(  Generates labels and annotations messages.

Args:
  resource: Resource type, can be deployment or preview.
  labels: dict[str,str], labels to be associated with the resource.
  annotations: dict[str,str], annotations to be associated with the resource.

Returns:
  Label and annotation messages.
r   r   )LabelsValuer   r   r   AnnotationsValue)resourcer   r   r   r   r   r   s          r9   r   r     s     . )) "mmF3
3
   333I3
 * N "33 "mmK8
8
 %%88S8N8
 4  
	,,

s   %B,
>%B2
)NNNNFNNNNNNNNNNNNr  )FN)NNNNNNNNNNNNNNN)NN):__doc__
__future__r   r   r   r(   r   r?   apitools.base.pyr   r   r   r   $googlecloudsdk.api_lib.infra_managerr	   googlecloudsdk.api_lib.storager
   r   googlecloudsdk.callioperG   (googlecloudsdk.command_lib.infra_managerr   r   r   googlecloudsdk.corer   r   r   googlecloudsdk.core.resourcer   googlecloudsdk.core.utilr   r   r   r   r   r:   rY   r_   rm   r   r   r   r   r   r   r   r   r  r  r  r   r  r8  rM   rP  rI  r   rD  r;   r9   <module>rj     sK   0 &  ' 	 
  % > ( C 6 7 > K ; H # ( ) ; * * 
 vD#>L]@,=@< #+Qh8OD 	H 7;(	V2(2*j;|8@v&*&	b -tn2'T-r;   