
    H              
          S 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SSKJr  SSKJ	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!r!Sr"Sr#Sr$Sr%Sr&\RN                  RP                  S\RN                  RR                  S\RN                  RT                  S0r+Sr,Sr-Sr.Sr/Sr0Sr1Sr2\/\0\1\24r3Sr4S r5S!r6S"r7S#r8\R                  " \5\/\6\0\7\1\8\205      r9S$r:\.\4\:4r; " S% S&\Rx                  5      r=S' r>S( r?S) r@S* rAS+ rBS, rCS- rDS. rES/ rFS0 rGS1 rHS2 rIS3 rJ S;S4 jrKS5 rLS6 rMS<S7 jrN\R                  " 5       rP\Q" \PR                  R                  R                  \PR                  R                  R                  \PR                  R                  R                  /5      rWS8 rXS9 rYS: rZg)=z8Functionality related to Cloud Functions v2 API clients.    )absolute_import)division)print_function)unicode_literalsN)encoding)
exceptions)projects_api)projects_util)apis)base)util)log)
properties)
console_io)progress_tracker)retrycloudfunctionsv2alphav2betav2zEAborted by user (background API operations may still be in progress).i` i  z-google.cloud.pubsub.topic.v1.messagePublishedz'google.cloud.storage.object.v1.archivedz&google.cloud.storage.object.v1.deletedz(google.cloud.storage.object.v1.finalizedz.google.cloud.storage.object.v1.metadataUpdatedzgoogle.pubsub.topic.publishzgoogle.storage.object.archivezgoogle.storage.object.deletezgoogle.storage.object.finalizez$google.storage.object.metadataUpdatez/providers/cloud.pubsub/eventTypes/topic.publishc                   $    \ rS rSrSrSrSrSrSrg)ApiEnvd                N)	__name__
__module____qualname____firstlineno__TESTAUTOPUSHSTAGINGPROD__static_attributes__r       /lib/googlecloudsdk/api_lib/functions/v2/util.pyr   r   d   s    	
$('	
$r(   r   c                  d    [         R                  R                  R                  R	                  SS9$ )zReturns the value of the core/project config prooerty.

Config properties can be overridden with command line flags. If the --project
flag was provided, this will return the value provided with the flag.
T)required)r   VALUEScoreprojectGetr   r(   r)   
GetProjectr0   k   s*     
					'	'	+	+T	+	::r(   c                 b    [         R                  U 5      n[        R                  " [        U5      $ )z*Returns the API messages module for GCFv2.)RELEASE_TRACK_TO_API_VERSIONgetr   GetMessagesModule	_API_NAMErelease_trackapi_versions     r)   r4   r4   u   %    ,00?+				;	77r(   c                     U [         R                  " [        [        5      L a  U R                  $ U [         R                  " [        [
        5      L a  U R                  $ U R                  $ )zAReturns corresponding GoogleCloudFunctionsV2(alpha|beta|ga)Stage.)r   r4   r5   	_V2_ALPHA GoogleCloudFunctionsV2alphaStage_V2_BETAGoogleCloudFunctionsV2betaStageGoogleCloudFunctionsV2Stagemessagess    r)   GetStagerB   {   sP    ''	9==4444)))X>>333///r(   c                     U [         R                  " [        [        5      L a  U R                  $ U [         R                  " [        [
        5      L a  U R                  $ U R                  $ )zHReturns corresponding GoogleCloudFunctionsV2(alpha|beta|ga)stateMessage.)r   r4   r5   r;   'GoogleCloudFunctionsV2alphaStateMessager=   &GoogleCloudFunctionsV2betaStateMessage"GoogleCloudFunctionsV2StateMessager@   s    r)   GetStateMessagerG      sP    ''	9==;;;4)))X>>:::666r(   c                       [         R                  R                  R                  S5      R	                  5       $ ! [         R
                   a     gf = f)z9Returns the API endpoint override property value for GCF.r   N)r   r,   api_endpoint_overridesPropertyr/   NoSuchPropertyErrorr   r(   r)   GetApiEndpointOverriderL      sJ    33<<	ce 
	'	' s   69 AAc                 b    [         R                  U 5      n[        R                  " [        U5      $ )z Returns an API client for GCFv2.)r2   r3   r   GetClientInstancer5   r6   s     r)   rN   rN      r9   r(   c                     [        S U 5      $ )zAReturns the list of string representations of the state messages.c                 `    SR                  [        U R                  5      U R                  5      $ )Nz[{}] {})formatstrseveritymessage)sts    r)   <lambda>)GetStateMessagesStrings.<locals>.<lambda>   s    !!#bkk"2BJJ?r(   )map)state_messagess    r)   GetStateMessagesStringsrZ      s    	?
 r(   c                 ,   U [         R                  " [        [        5      L a  U R                  $ U [         R                  " [        [
        5      L a  U R                  $ U [         R                  " [        [        5      L a  U R                  $ [        S5      e)zMReturns corresponding GoogleCloudFunctionsV2(alpha|beta|ga)OperationMetadata.zInvalid messages module.)
r   r4   r5   r;   ,GoogleCloudFunctionsV2alphaOperationMetadatar=   +GoogleCloudFunctionsV2betaOperationMetadata_V2_GA'GoogleCloudFunctionsV2OperationMetadataNotImplementedErrorr@   s    r)   GetOperationMetadatara      sq    ''	9==@@@4)))X>>???4)))V<<;;;
8
99r(   c                 ~    [         R                  " [        U 5      [         R                  " UR                  5      5      $ N)r   PyValueToMessagera   MessageToPyValuemetadata)rA   	operations     r)   _GetOperationMetadatarh      s1    		"	"8$	 2 23
 r(   c                     SR                  [        R                  " U 5      R                  SS5      R	                  5       5      $ )zGConverts NameValueValuesEnum into the header to use in progress stages.z[{}]_ )rQ   six	text_typereplacetitle)	name_enums    r)   _GetStageHeaderrq      s0    	s}}Y/77SAGGI	JJr(   c                      U R                   R                  U5      $ ! [        R                   a=  nUR                  [
        R                  R                  R                  :X  a   SnAge SnAff = f)z/Get operation and return None if doesn't exist.N)	projects_locations_operationsr/   apitools_exceptions	HttpErrorstatus_coderl   moveshttp_client	NOT_FOUND)clientrequesterrors      r)   _GetOperationr}      sX    
//33G<<		&	& 
CII11;;;	
s    A.2A)(A))A.c           	         [        X5      nUR                  (       a   [        R                  " UR                  5      e/ nUR                  (       as  [        X#5      nUR                   HX  nUR                  [        R                  " [        UR                  5      [        R                  " UR                  5      S95        MZ     X44$ )z$Returns the stages in the operation.)key)r}   r|   r   StatusToFunctionsErrorrf   rh   stagesappendr   Stagerq   namerl   rm   )rz   r{   rA   rg   r   operation_metadatastages          r)   _GetOperationAndStagesr      s    F,)__

+
+IOO
<<&.xC#**mm

 
 ejj)s}}UZZ/H + 
	r(   c                 t   U R                   R                  U5      nUR                  (       a2  [        R                  " UR                  [        UR                  5      S9e[        X45      nUR                   GH  nUR                  [        U5      R                  R                  L nUR                  [        U5      R                  R                  L nU(       d	  U(       d  Mj  [        UR                  5      n	UR                  U	5      (       a  M  UR!                  U	5      (       a  UR#                  U	5        UR$                  =(       d    Sn
U(       a  U
=(       d    SS-   n
OSn
UR&                  (       a$  U	S:X  a  U
SR)                  UR&                  5      -  n
UR+                  X5        U(       d  GM;  UR,                  (       a(  UR/                  U	[1        UR,                  5      5        GMt  UR3                  U	5        GM     UR4                  (       a'  UR6                  (       a  [8        R:                  " S5        U$ )z?Returns a Boolean indicating whether the request has completed.)error_message zIn progressz... BUILDzLogs are available at [{}]a  A custom IAM role was detected. If this role is used to manage or access your function, you must manually add the equivalent Cloud Run permissions and add the binding to your Cloud Run function. Refer to https://cloud.google.com/run/docs/reference/iam/permissions for details.)rs   r/   r|   r   r   OperationErrorToStringrh   r   staterB   StateValueValuesEnumIN_PROGRESSCOMPLETErR   r   
IsComplete	IsWaiting
StartStagerT   resourceUrirQ   UpdateStagestateMessagesCompleteStageWithWarningsrZ   CompleteStagedonecustomIamRoleDetectedr   warning)rz   r{   trackerrA   rg   r   r   stage_in_progressstage_complete	stage_keystage_messages              r)   _GetOperationAndLogProgressr      s   2266w?)__

+
+'=ioo'N  -XA!((ex)>>JJJ  	x)>>GGG  ^EJJI)$$ ### MM'RM$5?mmY'13::5;L;LMMm	1 ~			)).u/B/BC	
 	i(O )T ^^*@@KK	 
r(   c                 h   S nUR                  UR                  S9n[        R                  " S[        S9 n[
        R                  " [        S9n UR                  [        XU/U[        S9u  p) SSS5        Ub  W	U-  n	US	-  n[        R                  " UW	[        S9 nUR                   (       a  U	(       d  UsSSS5        $ [
        R                  " [        S9n UR                  ["        XXq/S
 [        S9n SSS5        U$ ! [
        R                   a0    [        R                  " SR                  UR                  5      5      ef = f! , (       d  f       N= f! [
        R                   a0    [        R                  " SR                  UR                  5      5      ef = f! , (       d  f       U$ = f)a  Wait for a long-running operation (LRO) to complete.

Args:
  client: The GCFv2 API client.
  messages: The GCFv2 message stubs.
  operation: The operation message response.
  description: str, the description of the waited operation.
  extra_stages: List[progress_tracker.Stage]|None, list of optional stages for
    the progress tracker to watch. The GCF 2nd api returns unexpected stages
    in the case of rollbacks.

Returns:
  cloudfunctions_v2_messages.Operation, the finished operation.
c                 H    U u  p#U(       + =(       a    UR                   (       + $ rc   r   )resrj   opr   s       r)   IsNotDoneAndIsMissingStages5WaitForOperation.<locals>.IsNotDoneAndIsMissingStages1  s    JB:%bgg+%r(   )r   zPreparing function)aborted_message)max_wait_ms)argsshould_retry_ifsleep_msz Operation {0} is taking too longNz...c                 $    U R                   (       + $ rc   r   )r   rj   s     r)   rV   "WaitForOperation.<locals>.<lambda>\  s
    BGGr(   )3CloudfunctionsProjectsLocationsOperationsGetRequestr   r   ProgressTracker_DEFAULT_ABORTED_MESSAGEr   RetryerMAX_WAIT_MSRetryOnResultr   SLEEP_MSWaitExceptionr   FunctionsErrorrQ   StagedProgressTrackerr   r   )
rz   rA   rg   descriptionextra_stagesr   r{   r   retryerr   s
             r)   WaitForOperationr     s   $& HH>> I ' '',Dmm4G!//
 *5	 0 i" 
lF +--6+C~~f  mm4G
''
%33	 ( i( 
?  %%
,
3
3INN
C  L  %%
,
3
3GLL
A  ( 
sC   E
DF"F"EAEE


EAFF""
F1c                    SR                  U R                  [        R                  " U R                  5      5      n[
        R                  " S[        5      nU R                  (       au  U R                   He  n[        R                  " UR                  [        R                  " U5      5      nUR                  c  UR                  c  MT  US[        U5      -   -  nMg     U$ )zReturns a human readable string representation from the operation.

Args:
  error: A string representing the raw json of the operation error.

Returns:
  A human readable string representation of the error.
z%OperationError: code={0}, message={1}r   
)rQ   codeencoderDecoderT   r   r4   r;   detailsr   rd   Statusre   r   )r|   r   rA   detail	sub_errors        r)   r   r   g  s     :@@jj'../- ##$4i@(
]]--++
//844V<i 
	#y'8'8'D 6y AAA   
r(   c                 F   ^^ [        UU4S jU R                   5       5      $ )zReturns whether the given SA has the given role bound in given policy.

Args:
  iam_policy: The IAM policy to check.
  sa_email: The service account to check.
  role: The role to check for.
c              3      >#    U  H9  nS R                  T5      UR                  ;   =(       a    UR                  T:H  v   M;     g7f)serviceAccount:{}N)rQ   membersrole).0br   sa_emails     r)   	<genexpr>!HasRoleBinding.<locals>.<genexpr>  s<      "!   *aii7JAFFdNJ"s   AA)anybindings)
iam_policyr   r   s    ``r)   HasRoleBindingr   ~  s%     
 "" 
 r(   c                   ^ ^ U=(       d    / n[         R                  " [        5       5      nSR                  T 5      n [        R
                  " U5      m[        UU 4S jU/UQ 5       5      (       a  g[        R                  R                  SR                  T X5      5        [        R                  " 5       =(       a$    [        R                  " SR                  UT 5      S9nU(       d  [        R                  " S5        g[        R                  " XEU5        [        R                  R                  S5        g! [        R                    a    [        R                  " S	UT U5         gf = f)
a  Prompts to bind the role to the service account in project level if missing.

If the console cannot prompt, a warning is logged instead.

Args:
  sa_email: The service account email to bind the role to.
  role: The role to bind if missing.
  alt_roles: Alternative roles to check that dismiss the need to bind the
    specified role.
  reason: Extra information to print explaining why the binding is necessary.
r   c              3   >   >#    U  H  n[        TTU5      v   M     g 7frc   )r   )r   rr   r   s     r)   r   ,PromptToBindRoleIfMissing.<locals>.<genexpr>  s     
O<Nq>*h22<Ns   Nz1Service account [{}] is missing the role [{}].
{}z,
Bind the role [{}] to service account [{}]?prompt_stringz/Manual binding of above role may be necessary.
zRole successfully bound.
zYour account does not have permission to check or bind IAM policies to project [%s]. If the deployment fails, ensure [%s] has the role [%s] before retrying.)r
   ParseProjectr0   rQ   r	   GetIamPolicyr   r   statusPrintr   	CanPromptPromptContinuer   AddIamPolicyBindingrt   HttpForbiddenError)r   r   	alt_rolesreasonproject_refmemberbindr   s   `      @r)   PromptToBindRoleIfMissingr     s$    o2)**:<8+%%h/& **;7J

OT<NI<N
OOOJJ<CCd	
 ! j&?&?ELL(
'D
 	kkDE$$[$?JJ12		/	/ 
KK2 		
s   4D7 3BD7  6D7 7-E'&E'c                     U R                    H  nUR                  U:X  d  M  Us  $    [        R                  U/ S9nU R                   R	                  U5        U$ )aD  Looks up the audit config for the given service.

If no audit config is found, a new one is created and attached to the given
policy.

Args:
  iam_policy: The IAM policy to look through.
  service: The service to find the audit config for.

Returns:
  The audit config for the given service or a blank new one if not found.
)serviceauditLogConfigs)auditConfigsr   _rm_messagesAuditConfigr   )r   r   acaudit_configs       r)   _LookupAuditConfigr     sV    $ ##b	zzWi $ ))'2)N,  .	r(   c           	      t   [        5       n[        R                  " U5      nSR                  U 5      n [        R
                  " U5      n[        X@5      n[        S UR                   5       5      nU[        :X  a  g[        R                  R                  SR                  X5      5        [         R"                  " 5       (       d  [        R                  " U5        g[        R                  R                  U5        [         R$                  " SR                  U 5      S9(       d  g[         Vs/ s H  owU;  d  M
  UPM     nnUR                  R'                  U Vs/ s H  n[(        R+                  US9PM     sn5         [        R,                  " X$S	S
9  [        R                  R                  S5        g! [        R                   a(    [        R                  " SR                  X5      5         gf = fs  snf s  snf ! [        R                   a(    [        R                  " SR                  U 5      5         gf = f)zPrompts to enable Data Access audit logs for the given service.

If the console cannot prompt, a warning is logged instead.

Args:
  service: The service to enable Data Access audit logs for.
z\If audit logs are not fully enabled for [{}], your function may fail to receive some events.zwYou do not have permission to retrieve the IAM policy and check whether Data Access audit logs are enabled for [{}]. {}Nc              3   8   #    U  H  oR                   v   M     g 7frc   logType)r   lcs     r)   r   4PromptToEnableDataAccessAuditLogs.<locals>.<genexpr>  s     L/K**/Ks   znSome Data Access audit logs are disabled for [{}]: https://console.cloud.google.com/iam-admin/audit?project={}z,
Enable all Data Access audit logs for [{}]?r   r   r   )update_maskz,Data Access audit logs successfully enabled.zkYou do not have permission to update the IAM policy and ensure Data Access audit logs are enabled for [{}].)r0   r
   r   rQ   r	   r   rt   r   r   r   r   setr   
_LOG_TYPESr   r   r   r   r   extendr   AuditLogConfigSetIamPolicy)	r   r.   r   warning_msgpolicyr   enabled_log_typesltlog_types_to_enables	            r)   !PromptToEnableDataAccessAuditLogsr    s    L'**73+&&,fWo 
	&&{3F $F4,L|/K/KLL*$
**DDJF
E 
				KK
**;		"	"CJJ


  '1Pj>O4OjP%%9LM9L2|""2".9LMk~NJJCDU 
	/	/ KK	CCI6D
 F QM 
	/	/ KK	3396'?s5   F2 *	G17G1G6=4G; 29G.-G.;9H76H7c                      [        5       n U c  [        R                  $ SU ;   a  [        R                  $ SU ;   a  [        R                  $ SU ;   a  [        R
                  $ [        R                  $ )z=Determine the cloudfunctions API env the gcloud cmd is using.ztest-cloudfunctionszautopush-cloudfunctionszstaging-cloudfunctions)rL   r   r&   r#   r$   r%   )
api_strings    r)   GetCloudFunctionsApiEnvr  ,  sZ    %'*;;j(;;*,??+>>	r(   rc   )Nr   )[__doc__
__future__r   r   r   r   enumapitools.base.pyr   r   rt   
frozendict+googlecloudsdk.api_lib.cloudresourcemanagerr	   r
   projects_api_util#googlecloudsdk.api_lib.functions.v2googlecloudsdk.api_lib.utilr   googlecloudsdk.callioper   calliope_base#googlecloudsdk.command_lib.projectsr   googlecloudsdk.corer   r   googlecloudsdk.core.consoler   r   googlecloudsdk.core.utilr   r   rl   r5   r;   r=   r^   r   ReleaseTrackALPHABETAGAr2   r   r   EA_PUBSUB_MESSAGE_PUBLISHEDEA_STORAGE_ARCHIVEEA_STORAGE_DELETEEA_STORAGE_FINALIZEEA_STORAGE_UPDATEEVENTARC_STORAGE_TYPESEF_PUBSUB_MESSAGE_PUBLISHEF_STORAGE_ARCHIVEEF_STORAGE_DELETEEF_STORAGE_FINALIZEEF_STORAGE_METADATA_UPDATE!EVENTFLOW_TO_EVENTARC_STORAGE_MAPLEGACY_PUBSUB_MESSAGE_PUBLISHPUBSUB_MESSAGE_PUBLISH_TYPESEnumr   r0   r4   rB   rG   rL   rN   rZ   ra   rh   rq   r}   r   r   r   r   r   r   GetMessagesr   	frozensetr   LogTypeValueValuesEnum
ADMIN_READ	DATA_READ
DATA_WRITEr   r   r  r  r   r(   r)   <module>r/     s2   ? &  % '  % >  D Z : , 9 E # * 2 8 8 * 
			 L 
 $$i##X!!4    N > < @ D  	  : 4 2 6 C $.$9$9*(, 1	; % ! 6 
  !  TYY ;8078	:K

(>D <@EP.&0f !,,.66AA66@@66AA 
6AHr(   