
    <                        S 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
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rS rS rS rS r S r!S r"S r#S r$S r%S r&S  r'S! r(S" r)S# r*S$ r+S% r,S& r-S' r.S( r/S) r0S* r1S+ r2S, r3S- r4S. r5S/ r6S0 r7 " S1 S2\Rp                  5      r9 " S3 S4\:5      r;g)5z*Utilities for "gcloud scheduler" commands.    )absolute_import)division)unicode_literalsN)
exceptions)
list_pager)apis)arg_parsers)app)	constants)log)
properties)	resourcesencoding)http_encodingzAtable(
     locationId:label="NAME",
     name:label="FULL_NAME")z2type.googleapis.com/google.pubsub.v1.PubsubMessagezcloudscheduler.projectsz!cloudscheduler.projects.locationsz,cloudscheduler.projects.locations.operationsc                  X    [         R                  " S[         R                  " S5      5      $ )Npubsub)r   GetMessagesModuleResolveVersion     0lib/googlecloudsdk/command_lib/scheduler/util.py_GetPubsubMessagesr   -   s     			$*=*=h*G	HHr   c                  0    [         R                  " SS5      $ Ncloudschedulerv1)r   GetClientInstancer   r   r   _GetSchedulerClientr   1       			 0$	77r   c                  0    [         R                  " SS5      $ r   )r   r   r   r   r   _GetSchedulerMessagesr"   5   r    r   c                     A g)zClear the value for a flag.Nr   )args    r   	ClearFlagr%   9   s    		r   c                     [        S5        g)z+Log message if job was successfully paused.pausedN_LogSuccessMessageunused_responseunused_argss     r   LogPauseSuccessr-   ?   s
    Xr   c                     [        S5        g)z,Log message if job was successfully resumed.resumedNr(   r*   s     r   LogResumeSuccessr0   D   s
    Yr   c                 `    [         R                  R                  SR                  U 5      5        g )NzJob has been {0}.)r   statusPrintformat)actions    r   r)   r)   I   s     **&--f56r   c                      [         R                  R                  [        R                  R
                  R                  R                  5       [        S9$ )N)
collection)	r   REGISTRYParser   VALUEScoreproject	GetOrFailPROJECTS_COLLECTIONr   r   r   ParseProjectr?   M   sA    				!	!$$..0$ 
" 
& &r   c                     [         R                  R                  U R                  S[        R
                  R                  R                  R                  5       0[        S9R                  5       $ )N	projectId)paramsr7   )r   r8   r9   namer   r:   r;   r<   r=   LOCATIONS_COLLECTIONSelfLink)tasks    r   LocationsUriFuncrG   S   sV    				!	!
ii:,,1199CCEF% 
" 
' (0xz2r   c                     U R                   R                  [        5        U R                   R                  [        5        g N)display_info	AddFormat_LOCATION_LIST_FORMAT
AddUriFuncrG   )parsers    r   AddListLocationsFormatsrO   Z   s,     56  !12r   c                 F    AU R                  5       UR                  l        U$ z-Change the job.name field to a relative name.RelativeNamejobrC   job_refargscreate_job_reqs      r   ModifyCreateJobRequestrY   _   s"    
#002.	r   c                    [        XU5        [        UR                  =(       d    UR                  5      UR                  R
                  l        UR                  (       a%  UR                  UR                  R
                  l        U$ )a  Add the pubsubMessage field to the given request.

Because the Cloud Scheduler API has a reference to a PubSub message, but
represents it as a bag of properties, we need to construct the object here and
insert it into the request.

Args:
  job_ref: Resource reference to the job to be created (unused)
  args: argparse namespace with the parsed arguments from the command line. In
      particular, we expect args.message_body and args.attributes (optional)
      to be AdditionalProperty types.
  create_job_req: CloudschedulerProjectsLocationsJobsCreateRequest, the
      request constructed from the remaining arguments.

Returns:
  CloudschedulerProjectsLocationsJobsCreateRequest: the given request but with
      the job.pubsubTarget.pubsubMessage field populated.
)rY   _EncodeMessageBodymessage_bodymessage_body_from_filerT   pubsubTargetdata
attributesrU   s      r   ModifyCreatePubsubJobRequestra   f   s`    & 7);
6466*8.!!&	__15N##.	r   c                 D    U R                  5       UR                  l        U$ rQ   rR   )rV   r,   update_job_reqs      r   SetRequestJobNamerd      s    #002.	r   c                 (   UR                   (       a  SUR                  R                  l        U$ UR                  (       d  UR
                  (       aA  [        UR                  =(       d    UR
                  5      UR                  R                  l        U$ )zBModify the App Engine update request to populate the message body.N)clear_message_bodyrT   appEngineHttpTargetbodyr\   r]   r[   unused_job_refrW   rc   s      r   SetAppEngineRequestMessageBodyrk      sm    	26N**/ 
 D772D8T883:N**/	r   c                 V   SnUR                   (       a  0 nOgUR                  (       d  UR                  (       aE  UR                  (       a  UR                  nUR                  (       a  UR                   H  nSX4'   M	     U(       a$  [        U5      UR                  R
                  l        U$ )zHModify the App Engine update request to update, remove or clear headers.N)clear_headersupdate_headersremove_headers_GenerateAdditionalPropertiesrT   rg   headersrj   rW   rc   rq   keys        r    SetAppEngineRequestUpdateHeadersrt      s    '	Gd11##g$$# % 5R6N**2	r   c                 (   UR                   (       a  SUR                  R                  l        U$ UR                  (       d  UR
                  (       aA  [        UR                  =(       d    UR
                  5      UR                  R                  l        U$ )z<Modify the HTTP update request to populate the message body.N)rf   rT   
httpTargetrh   r\   r]   r[   ri   s      r   SetHTTPRequestMessageBodyrw      sm    	)-N!!& 
 D77);8T88*:N!!&	r   c                 V   SnUR                   (       a  0 nOgUR                  (       d  UR                  (       aE  UR                  (       a  UR                  nUR                  (       a  UR                   H  nSX4'   M	     U(       a$  [        U5      UR                  R
                  l        U$ )zCModify the HTTP update request to update, remove, or clear headers.N)rm   rn   ro   rp   rT   rv   rq   rr   s        r   SetHTTPRequestUpdateHeadersry      s    '	Gd11##g$$# %,I-N!!)	r   c                     UR                   (       d  UR                  (       aA  [        UR                   =(       d    UR                  5      UR                  R                  l        U$ )z>Modify the Pubsub update request to populate the message body.)r\   r]   r[   rT   r^   r_   ri   s      r   SetPubsubRequestMessageBodyr{      sF    	$55+=8T88,:N##(	r   c                 V   SnUR                   (       a  0 nOgUR                  (       d  UR                  (       aE  UR                  (       a  UR                  nUR                  (       a  UR                   H  nSX4'   M	     U(       a$  [        U5      UR                  R
                  l        U$ )zHModify the Pubsub update request to update, remove, or clear attributes.N)clear_attributesupdate_attributesremove_attributesrp   rT   r^   r`   )rj   rW   rc   r`   rs   s        r    SetPubsubRequestUpdateAttributesr      s    *	J!7!7))j''#
 (1N2N##.	r   c                     [         R                  " 5       " U 5      n S[        U R                  5       5       VVs/ s H	  u  pXS.PM     snn0$ s  snnf )aC  Parse "--attributes" flag as an argparse type.

The flag is given as a Calliope ArgDict:

    --attributes key1=value1,key2=value2

Args:
  attributes: str, the value of the --attributes flag.

Returns:
  dict, a dict with 'additionalProperties' as a key, and a list of dicts
      containing key-value pairs as the value.
additionalPropertiesrs   value)r	   ArgDictsorteditems)r`   rs   r   s      r   ParseAttributesr      sW     ""$Z0*#J$4$4$6797zs '79
 9s   Ac                 @    SSSSSSSSSSS.
n[        X5      Ul        U$ )a  Constructs updateMask for patch requests of AppEngine targets.

Args:
  unused_ref: A resource ref to the parsed Job resource
  args: The parsed args namespace from CLI
  req: Created Patch request for the API call.

Returns:
  Modified request for the API call.
zappEngineHttpTarget.bodyzappEngineHttpTarget.relativeUriz,appEngineHttpTarget.appEngineRouting.versionz,appEngineHttpTarget.appEngineRouting.servicezappEngineHttpTarget.headers)
--message-body--message-body-from-filez--relative-urlz	--versionz	--servicez--clear-servicez--clear-relative-url--clear-headers--remove-headers--update-headers_GenerateUpdateMask
updateMask)
unused_refrW   reqapp_engine_fieldss       r   UpdateAppEngineMaskHookr      s=     3"<9AAG?677 't?#.	*r   c                 D    SSSSSSSSSSSS	S
.n[        X5      Ul        U$ )  Constructs updateMask for patch requests of PubSub targets.

Args:
  unused_ref: A resource ref to the parsed Job resource
  args: The parsed args namespace from CLI
  req: Created Patch request for the API call.

Returns:
  Modified request for the API call.
zhttpTarget.bodyzhttpTarget.urizhttpTarget.httpMethodzhttpTarget.headersz(httpTarget.oidcToken.serviceAccountEmailzhttpTarget.oidcToken.audiencez)httpTarget.oauthToken.serviceAccountEmailzhttpTarget.oauthToken.scopezhttpTarget.oidcToken.serviceAccountEmail,httpTarget.oidcToken.audience,httpTarget.oauthToken.serviceAccountEmail,httpTarget.oauthToken.scope)r   r   z--uriz--http-methodr   r   r   z--oidc-service-account-emailz--oidc-token-audiencez--oauth-service-account-emailz--oauth-token-scopez--clear-auth-tokenr   )r   rW   r   http_fieldss       r   UpdateHTTPMaskHookr     sD     *"3.-..
4>
5:(+( 't9#.	*r   c                 8    SSSSSSS.n[        X5      Ul        U$ )r   zpubsubTarget.datazpubsubTarget.topicNamezpubsubTarget.attributes)r   r   z--topicz--clear-attributesz--remove-attributesz--update-attributesr   )r   rW   r   pubsub_fieldss       r   UpdatePubSubMaskHookr   +  s0     ,"5)566- 't;#.	*r   c                    SSSSSSSSSSSSSS	S	S
.nU(       a  UR                  U5        / nU R                  5        H  nXB;   d  M
  UR                  X$   5        M     SR                  [	        [        [        U5      5      5      5      $ )zConstructs updateMask for patch requests.

Args:
  args: The parsed args namespace from CLI
  target_fields: A Dictionary of field mappings specific to the target.

Returns:
  String containing update mask for patch request.
descriptionscheduletimeZoneattemptDeadlinezretryConfig.retryCountzretryConfig.maxRetryDurationzretryConfig.minBackoffDurationzretryConfig.maxBackoffDurationzretryConfig.maxDoublings)z--descriptionz
--schedulez--time-zonez--clear-time-zonez--attempt-deadlinez--max-retry-attemptsz--clear-max-retry-attemptsz--max-retry-durationz--clear-max-retry-durationz--min-backoffz--clear-min-backoffz--max-backoffz--clear-max-backoffz--max-doublingsz--clear-max-doublings,)updateGetSpecifiedArgNamesappendjoinr   listset)rW   target_fieldsarg_name_to_fieldupdate_maskarg_names        r   r   r   B  s     %%-6$<<$B7=7=39#& ]++++-h$*45 . 
&c+./0	11r   c                 X    [         R                  " U SS9n[        R                  " U5      $ )zHTTP encodes the given message body.

Args:
  message_body: the message body to be encoded

Returns:
  String containing HTTP encoded message body.
zutf-8r   )r   Decoder   Encode)r\   message_body_strs     r   r[   r[   j  s'     __\GD			.	//r   c                 r    S[        U R                  5       5       VVs/ s H	  u  pXS.PM     snn0$ s  snnf )z8Format values_dict into additionalProperties-style dict.r   r   )r   r   )values_dictrs   r   s      r   rp   rp   w  sD     K%%'(( ,63#
&(
	 	s   3c                      [         R                  n U [        R                  ;   a$  [        R                  U    [         R                  ;   $ g)z@Returns whether the command being executed needs App Engine app.F)r   GCLOUD_COMMAND_ENV_KEYosenvironCOMMANDS_THAT_NEED_APPENGINE)gcloud_env_keys    r   _DoesCommandRequireAppEngineAppr     s6    33.rzz!::n%)O)OOO	r   c                       \ rS rSrSrSrg)RegionResolvingErrori  z@Error for when the app's region cannot be ultimately determined.r   N)__name__
__module____qualname____firstlineno____doc____static_attributes__r   r   r   r   r     s    Hr   r   c                   0    \ rS rSrSrS rS rS rS rSr	g)	AppLocationResolveri  zCallable that resolves and caches the app location for the project.

The "fallback" for arg marshalling gets used multiple times in the course of
YAML command translation. This prevents multiple API roundtrips without making
that class stateful.
c                     S U l         g rI   locationselfs    r   __init__AppLocationResolver.__init__  s	    DMr   c                 ^    U R                   c  U R                  5       U l         U R                   $ rI   )r   _ResolveAppLocationr   s    r   __call__AppLocationResolver.__call__  s&    }}..0dm==r   c                 |   [         R                  R                  R                  R	                  [         R                  R                  R
                  5        [        R                  " 5       (       aC  [         R                  R                  R                  R                  5       nU R                  U5      $ [        S5      e)z4Determines Cloud Scheduler location for the project.z<Please use the location flag to manually specify a location.)r   r:   billingquota_projectSetLEGACYr
   AppEngineAppExistsr;   r<   r=   _GetLocationr   )r   r<   s     r   r   'AppLocationResolver._ResolveAppLocation  s    
 ++//!!((*
!!&&..88:gw''
FH Hr   c                     [        5       n[        5       nUR                  SR                  U5      S9n[	        [
        R                  " UR                  USSSSS95      n[        U5      S:  ay  US   R                  R                  S   R                  n[        U5      S:  aB  [        5       (       d3  [        R                  " [        R                   R                  U5      5        U$ g	! ["        R$                   a     g	f = f)
z/Gets the location from the Cloud Scheduler API.zprojects/{})rC      	locationspageSize)
batch_sizelimitfieldbatch_size_attribute   r   N)r   r"   *CloudschedulerProjectsLocationsListRequestr4   r   r   YieldFromListprojects_locationslenlabelsr   r   r   r   warningr   #APP_ENGINE_DEFAULT_LOCATION_WARNINGapitools_exceptionsHttpNotFoundError)r   r<   clientmessagesrequestr   r   s          r   r    AppLocationResolver._GetLocation  s    "$f&(hCC##G, D .g

"
"''#-/0i 
Y1	Q<&&;;A>DDy>A&E&G&G
++;;BB8LN00 s   C%C) )D ?D r   N)
r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s    
Hr   r   )<r   
__future__r   r   r   r   apitools.base.pyr   r   r   googlecloudsdk.api_lib.utilr   googlecloudsdk.callioper	    googlecloudsdk.command_lib.tasksr
   r   googlecloudsdk.corer   r   r   googlecloudsdk.core.utilr   r   rL   _PUBSUB_MESSAGE_URLr>   rD   OPERATIONS_COLLECTIONr   r   r"   r%   r-   r0   r)   r?   rG   rO   rY   ra   rd   rk   rt   rw   ry   r{   r   r   r   r   r   r   r[   rp   r   Errorr   objectr   r   r   r   <module>r      s   1 &  ' 	 > ' , / 0 6 * # * ) - 2   K / : F I88
 
7&23
6$"",6 F.%2P
0	I:++ I4& 4r   