
                            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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rSrSrSr " S S\R<                  5      rS r S r! " S S\"5      r#g)z0Utilities for Eventarc gke-destinations command.    )absolute_import)division)unicode_literals)
exceptions)projects_api)common)serviceusage)apis)util)log)
properties)
console_io)retryzus-central1zfake-trigger-id)zroles/container.developerzroles/iam.serviceAccountAdminzroles/compute.vieweri N  c                       \ rS rSrSrSrg)!GKEDestinationInitializationError)   zSError when failing to initialize project for Cloud Run for Anthos/GKE destinations. N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       7lib/googlecloudsdk/api_lib/eventarc/gke_destinations.pyr   r   )   s    [r   r   c                 b    AAAU [         R                  :H  =(       d    U [         R                  :H  $ )a  Whether to retry the request when receiving errors.

Args:
  exc_type: type of the raised exception.
  exc_value: the instance of the raise the exception.
  exc_traceback: Traceback, traceback encapsulating the call stack at the the
    point where the exception occurred.
  state: RetryerState, state of the retryer.

Returns:
  True if exception and is due to NOT_FOUND or INVALID_ARGUMENT.
)apitools_exceptionsHttpBadRequestErrorHttpNotFoundError)exc_type	exc_valueexc_tracebackstates       r   _ShouldRetryHttpErrorr$   -   s3     
)==
= <
);;
;=r   c                     [         R                  R                  R                  R	                  SS9n[
        R                  " X5      nUS   $ )ai  Gets (or creates) the P4SA for Eventarc in the given project.

If the P4SA does not exist for this project, it will be created. Otherwise,
the email address of the existing P4SA will be returned.

Args:
  service_name: str, name of the service for the P4SA, e.g.
    eventarc.googleapis.com

Returns:
  Email address of the Eventarc P4SA for the given project.
Trequiredemail)r   VALUEScoreprojectGetr	   GenerateServiceIdentity)service_nameproject_nameresponses      r   _GetOrCreateP4SAr1   ?   sD     ""''//33T3B,11,M(	'	r   c                   d    \ rS rSrSrS rS rS rS r\	R                  " S\SS	\S
9S 5       rSrg)GKEDestinationsClientQ   zMWrapper client for setting up Eventarc Cloud Run for Anthos/GKE destinations.c                     [         R                  " U5      U l        [        R                  " [         R
                  U R                  5      nUR                  U l        UR                  U l	        g )N)
r   GetApiVersion_api_versionr
   GetClientInstanceAPI_NAMEMESSAGES_MODULE	_messagesprojects_locations_triggers_service)selfrelease_trackclients      r   __init__GKEDestinationsClient.__init__T   sK    ,,];D##FOOT5F5FGF++DN66DMr   c                      U R                  5         [        R                  " U R
                  5      n[        U5      nU(       d  [        S5      eU R                  U[        5        g! [        R                   a     Njf = f)a  Force create the Eventarc P4SA, and grant IAM roles to it.

1) First, trigger the P4SA JIT provision by trying to create an empty
trigger, ignore the HttpBadRequestError exception, then call
GenerateServiceIdentity to verify that P4SA creation is completed.
2) Then grant necessary roles needed to the P4SA for creating GKE triggers.

Raises:
  GKEDestinationInitializationError: P4SA failed to be created.
zGFailed to initialize project for Cloud Run for Anthos/GKE destinations.N)
_CreateEmptyTriggerr   r   r   GetApiServiceNamer7   r1   r   _BindRolesToServiceAccount_ROLES)r>   r.   
p4sa_emails      r   InitServiceAccount(GKEDestinationsClient.InitServiceAccountZ   st    
  ++D,=,=>L!,/J-
S  	##J7 22 
s   A& &A=<A=c                    [         R                  R                  R                  R	                  SS9nSR                  U[        5      nU R                  R                  U[        S9nU R                  R                  U5      $ )zAttempt to create an empty trigger in us-central1 to kick off P4SA JIT provision.

The create request will always fail due to the empty trigger message
payload, but it will trigger the P4SA JIT provision.

Returns:
  A long-running operation for create.
Tr&   zprojects/{}/locations/{})parent	triggerId)r   r)   r*   r+   r,   format	_LOCATIONr;   .EventarcProjectsLocationsTriggersCreateRequest_TRIGGER_IDr=   Create)r>   r+   rL   reqs       r   rD   )GKEDestinationsClient._CreateEmptyTriggers   so     $$,,00$0?G'..w	BF
..
G
G H .C==$$r   c                 H   SR                  [        U5       Vs/ s H  nSR                  U5      PM     sn5      n[        R                  R                  SR                  X5      5        [        R                  " SSSSS9  [        R                  " [        R                  R                  R                  R                  SS95      nS	R                  U5      nU Vs/ s H  o6U4PM     nnU R                  XW5        [        R                  R                  S
5        gs  snf s  snf )zBinds roles to the provided service account.

Args:
  sa_email: str, the service account to bind roles to.
  roles: iterable, the roles to be bound to the service account.

z- {}zTo use Eventarc with Cloud Run for Anthos/GKE destinations, Eventarc Service Agent [{}] needs to be bound to the following required roles:
{}FTz$
Would you like to bind these roles?)defaultthrow_if_unattendedprompt_stringcancel_on_nor&   zserviceAccount:{}zRoles successfully bound.N)joinsortedrN   r   statusPrintr   PromptContinueprojects_utilParseProjectr   r)   r*   r+   r,   _AddIamPolicyBindingsWithRetry)r>   sa_emailrolesroleformatted_rolesproject_ref
member_strmember_roless           r   rF   0GKEDestinationsClient._BindRolesToServiceAccount   s     ii Ot!4 OPOJJ	AAGB'(
  =	  ,,&&**D*9;K$++H5J38954&5L9''BJJ01# !P :s   DD
   g?d   )max_retrialsmax_wait_msexponential_sleep_multipliersleep_msshould_retry_ifc                 .    [         R                  " X5      $ )zAdds iam bindings to project_ref's iam policy, with retry.

Args:
  project_ref: The project for the binding
  member_roles: List of 2-tuples of the form [(member, role), ...].

Returns:
  The updated IAM Policy
)r   AddIamPolicyBindings)r>   rg   ri   s      r   rb   4GKEDestinationsClient._AddIamPolicyBindingsWithRetry   s      ,,[GGr   )r7   r;   r=   N)r   r   r   r   r   rA   rI   rD   rF   r   RetryOnException_MAX_WAIT_TIME_IN_MSr$   rb   r   r   r   r   r3   r3   Q   sI    U782%24 	&#&+-
H-
Hr   r3   N)$r   
__future__r   r   r   apitools.base.pyr   r   +googlecloudsdk.api_lib.cloudresourcemanagerr   googlecloudsdk.api_lib.eventarcr   googlecloudsdk.api_lib.servicesr	   googlecloudsdk.api_lib.utilr
   #googlecloudsdk.command_lib.projectsr   r`   googlecloudsdk.corer   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   rO   rQ   rG   rv   InternalErrorr   r$   r1   objectr3   r   r   r   <module>r      s{    7 &  ' > D 2 8 , E * # * 2 *	
" ! \
(@(@ \=$$[HF [Hr   