
    A                     n   d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddl
mZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ  ej6                  d      ZdZ	 	 	 	 	 	 	 	 	 d$defdZd Z d Z!dedededdfdZ"	 d%dZ#d Z$d Z%d Z&d  Z'd! Z(dede)fd"Z*d# Z+y)&Creates an image from Source.    N)encoding)
exceptions)cloudbuild_util)global_methods)apis)waiter)base)submit_util)artifact_registry)stages)sources)types)
properties)	resourceszSprojects/(?P<projectId>[^/]*)/locations/(?P<location>[^/]*)/builds/(?P<build>[^/]*)z/cloud-run-source-deployregionc                    |re| j                  t        j                         | j                  d       t	        j
                  ||       | j                  t        j                         d}d}| j                  t        j                         |r4| j                  d       t        |||       t        j                  |      }n)| j                  d       t        j                  ||||      }| j                  t        j                         t        ||||
||||||||      }	 t        | |      \  }}}|r;|d   dk7  r3| j#                  t        j$                  ddj'                  |	      
       y| j                  t        j$                         |d   d   d   d   ||d   ||d   fS # t        j                  $ r$}|
s|	r|t!        | |||||      \  }}Y d}~d}~ww xY w)r   zCreating Container Repository.Nz+Using the source from the specified bucket.Uploading sources.)remote_sourcestatusSUCCESSzCContainer build failed and logs are available at [{build_log_url}].build_log_url)message)NNNNNresultsimagesr   digestidname)
StartStager   CREATE_REPOUpdateHeaderMessager   CreateRepositoryCompleteStageUPLOAD_SOURCE_ValidateCmekDeploymentr   GetGcsObjectUpload_PrepareSubmitBuildRequest_SubmitBuildapitools_exceptionsHttpNotFoundError_CreateImageWithoutSubmitBuild	FailStageBUILD_READYformat)trackerbuild_imagebuild_source
build_packrepo_to_createrelease_trackalready_activated_servicesr   resource_refdelegate_builds
base_imageservice_accountbuild_worker_poolbuild_machine_typebuild_env_varsenable_automatic_updatessource_bucketkms_keybase_image_from_buildsourcesubmit_build_requestresponse_dictr   es                           <lib/googlecloudsdk/command_lib/run/sourcedeploys/deployer.pyCreateImagerH   -   s	   * v))* @A&&2 &,,-&	V))* MNk7 !!,/F 45^^L&,NF	,,-3:F;7M="7, }X.);77=v+ 8> 8  	 (&,,-i *1-h7df A 
	.	. _ g $B"$ M=s    F% %G8GGc                 R    t        | ||||      \  }}t        | |||      \  }}	||	fS )zSCreates an image from source by calling GCB direcly, bypassing the SubmitBuild API.)skip_activation_prompt)_PrepareBuildConfig_BuildFromSource)
r1   r2   r3   r4   r7   r   build_messagesbuild_configrE   r   s
             rG   r-   r-      sL     "5"., "27	"- 
	%%    c                    t        j                         }|rwt        j                  |      }|?|d   j	                  dg       }|j                  d|        |d   j                  d|i       t        j                  j                  j                  j                  d       t        j                  |fi ddd|ddd	dd
dddd|ddddddddddddddddddddddd|dddddd}|K|j                  d   j                  dk(  sJ |j                  d   j                   j#                  dd | g       |j%                  |j'                  |j(                  |j                  |j*                  !      "      |_        ||fS | j/                  t0        j2                         | j5                  d#       t        j                  j                  j                  j                  d       t        j                  |fi ddd|ddd	dd
dddd|ddddddddddddddddddddddd|dddd}| j7                  t0        j2                         ||fS )$z%Prepare build config for cloud build.Nr   envszGOOGLE_LABEL_SOURCE=Fno_cachemessagessubstitutions
arg_configis_specified_sourceT	no_sourcerC   gcs_source_staging_dirignore_filearg_gcs_log_dirarg_machine_typearg_disk_sizearg_worker_poolarg_dirarg_revisionarg_git_source_dirarg_git_source_revisionarg_service_account	buildpack	hide_logsskip_set_source
client_tag	gcloudrunz"gcr.io/cloud-builders/gcb-internalz--labelzgoogle.source=bucketobject
generation)storageSourcer   )r   GetMessagesModuler   GetGsutilUrigetappendupdater   VALUESbuilds
use_kanikoSetr   CreateBuildConfigstepsr   argsextendSourceStorageSourceri   rk   rC   r    r   r%   r"   r$   )	r1   r2   r3   r4   r   rM   urirQ   rN   s	            rG   rK   rK      sl    #446. 

}
-C]vr*d
kk(./mFD>* ''++E200   	
  !    $        !"  #$ !%%& !'( )* +, -. /L6 "''+OOOO  ''nSE4J(KL(//$22 '' %%$// 3 
 0 LL 
	%%= v++, 45''++E200   	
  !    $        !"  #$ !%%& !'( )* +, -L0 &../		%%rO   rC   image_repositoryrA   returnc                     |syt        j                  |       st        j                  d|  d      |st        j                  d      t	        |      rt        j                  d      y)z/Validate the CMEK parameters of the deployment.NzInvalid source location: z. Deployments encrypted with a customer-managed encryption key (CMEK) expect the source to be passed in a pre-configured Cloud Storage bucket. See https://cloud.google.com/run/docs/securing/using-cmek#source-deploy for more details.zDeployments encrypted with a customer-managed encryption key (CMEK) require a pre-configured Artifact Registry repository to be passed via the `--image` flag. See https://cloud.google.com/run/docs/securing/using-cmek#source-deploy for more details.a  The default Artifact Registry repository can not be used when deploying with a customer-managed encryption key (CMEK). Please provide a pre-configured repository using the `--image` flag. See https://cloud.google.com/run/docs/securing/using-cmek#source-deploy for more details.)r   IsGcsObjectr   ArgumentError_IsDefaultImageRepository)rC   r}   rA   s      rG   r&   r&     s     

			V	$

"
"
#F8 , 	  


"
"	  /0

"
"	  1rO   c                    t         j                  }t        j                  |d|d||      \  }}d|j                   d| d|j
                   }t        j                  j                  |d      }|j                  }	| j                  t        j                         | j                  d       | j                  t        j                  d	j                  |	
             t!        |      }
|
|	fS )zGBuild an image from source if a user specifies a source when deploying.T)rd   build_regionrJ   	projects//locations//operations/(cloudbuild.projects.locations.operations
collectionBuilding Container.(Logs are available at [{build_log_url}].r   )r   DEFAULT_REGIONr   Build	projectIdr   r   REGISTRYParseRelativeNamelogUrlr    r   r/   r"   UpdateStager0   _PollUntilBuildCompletes)r1   rM   rN   rJ   r   build_build_opbuild_op_refr   rE   s              rG   rL   rL   .  s     !//,
3(% )\N,uxxjY(##55E 6 , ,,-	V''(	34	077% 8  +<8-		%%rO   c                 $   t        j                  t        j                  d      }dj	                  t
        j                  j                  j                  j                  d      |      }|j                  |j                  |j                  |j                        }t        |      }|rd}|d   j                  d	d      }|d   j                  d
g       D ](  }|j!                  d      s|j#                  d      d   }* |	k|j$                  j'                  t)        |	j+                               D cg c],  \  }}|j$                  j&                  j-                  ||      . c}}      }	|j/                  ||j1                  ||d   j                  d      |j%                  |||	|
|      d||||t3        ||      	            S |j/                  ||j1                  || d|j5                         ||||t3        ||      	            S c c}}w )zBUpload the provided build source and prepare submit build request.v2z%projects/{project}/locations/{region}T)required)projectr   rh   Nr   project_descriptorrQ   GOOGLE_FUNCTION_TARGET=   )keyvalue)additionalPropertiesimage)	baseImagefunctionTargetenvironmentVariablesenableAutomaticUpdatesprojectDescriptor)	rl   imageUribuildpackBuilddockerBuildtagsserviceAccount
workerPoolmachineTypereleaseTrack)parent"googleCloudRunV2SubmitBuildRequest)r   rm   r   SERVERLESS_API_NAMEr0   r   rr   corer   GetGoogleCloudRunV2StorageSourceri   r   rk   _GetBuildTagsro   
startswithsplitGoogleCloudRunV2BuildpacksBuildEnvironmentVariablesValuesorteditemsAdditionalProperty'RunProjectsLocationsBuildsSubmitRequest"GoogleCloudRunV2SubmitBuildRequest_MapToReleaseTrackEnumGoogleCloudRunV2DockerBuild)docker_imager4   r   r:   rC   r8   r;   r<   r=   r>   r?   r6   rS   r   storage_sourcer   function_targetr   envr   r   s                        rG   r)   r)   M  sF    ##N$F$FM(299$$,,00$0? : & 99]]6;;6;L;L : . 
|	$$O#A**+?F!}  ,	0	1))C.+ - !??YY
 !'~';';'= >	  !?*#u 66PPcc d  !?	  Z n ;;+3+V+V(]&&w/#CC$.%3'?"4 D  *(*/xH ,W ,
 <  , 
	9	9)1)T)T&::<(&(-mXF *U 
* 
: 
 ; s   41H
c                 T    t        j                  |        d| j                          gS )Nr   )r   GetKindName)r8   s    rG   r   r     s*    ]]<()<+<+<+>*?
@	AArO   c                 V   t        j                  t        j                  d      }t	        j
                         }|j                  j                  |      }|j                  r| j                  |j                         |j                  }t        j                  |j                        }t        j                  |j                  |      j                   }t#        |j$                        }d|j&                   d| d|j(                   }	t*        j,                  j/                  |	d      }
|j0                  }| j3                  t4        j6                         | j9                  d       | j;                  t4        j6                  dj=                  |	             t?        |
      }|||j@                  fS )
a  Call Build API to submit a build.

  Arguments:
    tracker: StagedProgressTracker, to report on the progress of releasing.
    submit_build_request: SubmitBuildRequest, the request to submit build.

  Returns:
    response_dict: Build resource returned by Cloud build.
    build_log_url: The url to build log
    build_response.baseImageUri: The rectified uri of the base image that should
    be used in automatic base image update.
  r   r   r   r   r   r   r   r   r   )!r   GetClientInstancer   r   r   rm   projects_locations_buildsSubmitbaseImageWarning
AddWarningbuildOperationr   MessageToJsonmetadataJsonToMessageBuildOperationMetadatar   _GetBuildRegionr   r   r   r   r   r   r   r    r   r/   r"   r   r0   r   baseImageUri)r1   rD   
run_clientrM   build_responser   jsonr   r   r   r   r   rE   s                rG   r*   r*     sr     %%n&H&H$O*"446.77>>. $$~667**(			 1 1	2$

 
 ++T	E  !,,U__%[l588*	U$##55
A 6 , ,,-	V''(	34	077% 8  +<8-	~'B'B	BBrO   c                     t        j                         }t        j                  |j                  |j
                        }t        j                  ||       }t        j                  |j                        S )N)
r   r   r	   CloudOperationPollerprojects_builds
operationsPollUntilDoner   MessageToPyValueresponse)r   clientpoller	operations       rG   r   r     s\    ,,.&&&f//& ""6<8)		"	"9#5#5	66rO   c                 n    t         j                  |       }|r|j                  d      S t        d|        )NlocationzInvalid build name: )_BUILD_NAME_PATTERNmatchgroup
ValueError)
build_namer   s     rG   r   r     s7    

#
#J
/%
;;z"")*677rO   c                     t         | v S )z2Checks if the image repository is the default one.)_DEFAULT_IMAGE_REPOSITORY_NAME)r}   s    rG   r   r     s    	'+;	;;rO   c                     d}| rE| t         j                  j                  k7  r(|j                  j                  } || j
                        }|S )z-Returns the enum value for the release track.N)calliope_baseReleaseTrackGAr   ReleaseTrackValueValuesEnumr   )r6   rS   release_track_enum_valuerelease_track_enum_clss       rG   r   r     sK    !}(B(B(E(EE33OO   6m6H6HI	!!rO   )	FNNNNNFNN)F),__doc__reapitools.base.pyr   r   r+   !googlecloudsdk.api_lib.cloudbuildr   googlecloudsdk.api_lib.runr   googlecloudsdk.api_lib.utilr   r	   googlecloudsdk.callioper
   r   !googlecloudsdk.command_lib.buildsr   googlecloudsdk.command_lib.runr   r   ,googlecloudsdk.command_lib.run.sourcedeploysr   r   googlecloudsdk.corer   r   compiler   r   strrH   r-   rK   r&   rL   r)   r   r*   r   r   boolr   r    rO   rG   <module>r     s    $ 	 % > = 5 , . 9 9 < 5 1 @ > * ) !bjjY  "<   "%d dN&2\&~#&14	F CH&>L^B-C`78< < <
"rO   