
    8                        d 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ZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ% G d de	jL                        Z' G d  d!e	jL                        Z(	 d>d"Z)d?d#Z*d?d$Z+d?d%Z,d@d&Z-d' Z.d( Z/d) Z0d* Z1d@d+Z2d, Z3d- Z4d. Z5d@d/Z6d0 Z7d1 Z8d2 Z9d3 Z:d4 Z;d5 Z<d6 Z=d7 Z>d8 Z?d9 Z@d: ZAd; ZBd< ZCd= ZDy)Az9A library that is used to support Cloud Pub/Sub commands.    )absolute_import)division)unicode_literals)subscriptions)topics)
exceptions)util)log)
properties)	resources)resource_projector)timesNz%Y-%m-%dT%H:%M:%S.%fZzpubsub.projects.topicszpubsub.topics.publishzpubsub.projects.snapshotszpubsub.snapshots.listzpubsub.projects.subscriptionszpubsub.subscriptions.ackzpubsub.subscriptions.listzpubsub.subscriptions.mod_ackzpubsub.subscriptions.mod_configzpubsub.subscriptions.pullzpubsub.subscriptions.seekpubsub.projects.schemasa  Using --push-auth-service-account requires specifying --push-endpoint. This
command will continue to run while ignoring --push-auth-service-account, but
will fail in a future version. To correct a subscription configuration, run:
  $ gcloud pubsub subscriptions update SUBSCRIPTION \
      --push-endpoint=PUSH_ENDPOINT \
      --push-auth-service-account={SERVICE_ACCOUNT_EMAIL} [...]
a  Using --push-auth-token-audience requires specifying both --push-endpoint and
--push-auth-service-account. This command will continue to run while ignoring
--push-auth-token-audience, but will fail in a future version. To correct a
subscription configuration, run:
  $ gcloud pubsub subscriptions update SUBSCRIPTION \
      --push-endpoint={PUSH_ENDPOINT} \
      --push-auth-service-account={SERVICE_ACCOUNT_EMAIL} \
      --push-auth-token-audience={OPTIONAL_AUDIENCE_OVERRIDE} [...]
c                       e Zd ZdZy)InvalidArgumentErrorz$The user provides invalid arguments.N)__name__
__module____qualname____doc__     -lib/googlecloudsdk/command_lib/pubsub/util.pyr   r   J   s    ,r   r   c                   "     e Zd ZdZ fdZ xZS )RequestsFailedErrorz4Indicates that some requests to the API have failed.c                 l    t         t        |   dj                  |dj	                  |                   y )Nz/Failed to {action} the following: [{requests}].,)actionrequests)superr   __init__formatjoin)selfr   r   	__class__s      r   r    zRequestsFailedError.__init__Q   s5    	
t-9@@CHHX$6 	A 	89r   )r   r   r   r   r    __classcell__)r$   s   @r   r   r   N   s    <9 9r   r   c                     | r| S |S Nr   )original_messagedefault_messages     r   CreateFailureErrorMessager*   W   s     .	B?Br   c                 h    t        |      }t        j                  j                  | d|it              S N
projectsIdparams
collection)_GetProjectr   REGISTRYParseSNAPSHOTS_COLLECTION)snapshot_name
project_ids     r   ParseSnapshotr7   ]   s9    :&*				!	!-*6
)C-A 
" 
C Cr   c                 h    t        |      }t        j                  j                  | d|it              S r,   )r1   r   r2   r3   SUBSCRIPTIONS_COLLECTION)subscription_namer6   s     r   ParseSubscriptionr;   d   s:    :&*				!	!"3*6
)C-E 
" 
G Gr   c                 h    t        |      }t        j                  j                  | d|it              S r,   )r1   r   r2   r3   TOPICS_COLLECTION)
topic_namer6   s     r   
ParseTopicr?   k   s9    :&*				!	!**6
)C-> 
" 
@ @r   c                 B    t        |       } t        j                  |       S r'   )r1   projects_utilParseProjectr6   s    r   rB   rB   r   s    :&*		#	#J	//r   c                 r    | xs4 t         j                  j                  j                  j	                  d      S )NTrequiredr   VALUEScoreprojectGetrC   s    r   r1   r1   w   s-    		Hz((--559949HHr   c                 d    t        | t              r| d   }n| }t        |      j                         S )Nname)
isinstancedictr7   SelfLink)snapshotrM   s     r   SnapshotUriFuncrR   {   s/    $FDD	t		%	%	''r   c                     d }t        | t              r| d   }| d   }nt        | t              r| }n| j                  }t	        ||      j                         S )NsubscriptionId	projectId)rN   rO   strrM   r;   rP   )subscriptionrJ   rM   s      r   SubscriptionUriFuncrX      sV    'd#()D;'G,$DD	4	)	2	2	44r   c                 x    t        | t              r| d   }n| j                  }t        |      j	                         S )NtopicId)rN   rO   rM   r?   rP   )topicrM   s     r   TopicUriFuncr\      s3    tD::D	D		"	"	$$r   c                 h   | j                   }t        | dd      }t        | dd      }|8||4t        j                  t        j                  |xs d|xs d|             n-|+|)t        j                  t        j                  |             |t        |       rt        d      y|xs t        j                         }d}||j                  j                  ||      }d}t        |       r)t        | d	d
      }|j                  j                  |      }|j                  j                  |||      S )z.Parses configs of push subscription from args.SERVICE_ACCOUNT_EMAILNOPTIONAL_AUDIENCE_OVERRIDEPUSH_ENDPOINT)r`   r^   r_   )r^   z>argument --push-no-wrapper: --push-endpoint must be specified.)serviceAccountEmailaudiencepush_no_wrapper_write_metadataF)writeMetadata)pushEndpoint	oidcToken	noWrapper)push_endpointgetattrr
   warning7PUSH_AUTH_TOKEN_AUDIENCE_MISSING_REQUIRED_FLAGS_WARNINGr!   2PUSH_AUTH_SERVICE_ACCOUNT_MISSING_ENDPOINT_WARNINGHasNoWrapperr   r   SubscriptionsClientmessages	OidcToken	NoWrapper
PushConfig)argsclientrh   service_account_emailrb   
oidc_token
no_wrapperwrite_metadatas           r   ParsePushConfigry      sd   $$-!$(?FT7>( 4<KK?FF':?"7 #'&'/	 	G 	
 (]-BKK:AA"7 	B 	
 D 
J  8]668&* &**1H + FJ *$T#CUKN***HJ		#	# J* 
$ 
N Nr   c                     t        | dd      S )Npush_no_wrapperF)ri   )rs   s    r   rm   rm      s    	(%	00r   c                 V    t        j                  | t        t         j                        S )N)fmttzinfo)r   FormatDateTimeSEEK_TIME_FORMATUTC)times    r   FormatSeekTimer      s    			d(8	KKr   c                 2    t        j                  |       dz   S )zFormats a duration argument to be a string with units.

  Args:
    duration (int): The duration in seconds.
  Returns:
    unicode: The formatted duration.
  s)six	text_type)durations    r   FormatDurationr      s     
x	 3	&&r   c                     |xs t        j                         }g }| r\t        t        j                  |             D ];  \  }}|j                  |j                  j                  j                  ||             = |S )a&  Parses attribute_dict into a list of AdditionalProperty messages.

  Args:
    attribute_dict (Optional[dict]): Dict containing key=value pairs
      to parse.
    messages (Optional[module]): Module containing pubsub proto messages.
  Returns:
    list: List of AdditionalProperty messages.
  )keyvalue)	r   GetMessagesModulesortedr   	iteritemsappendPubsubMessageAttributesValueAdditionalProperty)attribute_dictro   
attributesr   r   s        r   ParseAttributesr      sw     3113(*S]]>:;
U

 
 
0
0
C
C D  <
 
r   c                 T    t        j                  |       }| j                  |d<   |d= |S )zCreates a serializable from a Cloud Pub/Sub Topic operation for display.

  Args:
    topic: (Cloud Pub/Sub Topic) Topic to be serialized.
  Returns:
    A serialized object representing a Cloud Pub/Sub Topic
    operation (create, delete).
  rZ   rM   )r   MakeSerializablerM   )r[   topic_display_dicts     r   TopicDisplayDictr      s2     *::5A"'**Y 	r   c           	         d}d}| j                   r.| j                   j                  r| j                   j                  }d}| j                  | j                  ||| j                  t        | j                        | j                  | j                  dS )a  Creates a serializable from a Cloud Pub/Sub Subscription op for display.

  Args:
    subscription: (Cloud Pub/Sub Subscription) Subscription to be serialized.
  Returns:
    A serialized object representing a Cloud Pub/Sub Subscription
    operation (create, delete, update).
   pullpush)rT   r[   typere   ackDeadlineSecondsretainAckedMessagesmessageRetentionDurationenableExactlyOnceDelivery)	
pushConfigre   rM   r[   r   boolr   r   r   )rW   rh   subscription_types      r   SubscriptionDisplayDictr     s     -++"--::m  %))!!#(;;!,"B"BC"."G"G#/#I#I	
 	r   c                 J    | j                   | j                  | j                  dS )a  Creates a serializable from a Cloud Pub/Sub Snapshot operation for display.

  Args:
    snapshot: (Cloud Pub/Sub Snapshot) Snapshot to be serialized.

  Returns:
    A serialized object representing a Cloud Pub/Sub Snapshot operation (create,
    delete).
  )
snapshotIdr[   
expireTime)rM   r[   r   )rQ   s    r   SnapshotDisplayDictr     s%     MM~~''
 r   c                    t        j                  |       }| j                  j                  rdnd|d<   t	        | j
                        }|j                  |d<   |j                  |d<   t        | j                        }|j                  |d<   |S )z3Returns a subscription dict with additional fields.PUSHPULLr   rU   rT   rZ   )r   r   r   re   r;   rM   r-   subscriptionsIdr?   r[   topicsId)rW   resultsubscription_ref
topic_infos       r   ListSubscriptionDisplayDictr   /  s    ..|<&)44AA6v&.&|'8'89(33&-==&	,,,-* ))&	-r   c                     t        j                  |       }t        | j                        }| j                  |d<   |j                  |d<   |d= |S )Nr[   rZ   rM   )r   r   r?   rM   r   )r[   
topic_dict	topic_refs      r   ListTopicDisplayDictr   ;  sL    !2259*$)

*W#,,*Y	r   c                     t        j                  d| i      }t        |       }|j                  |d<   |j                  |d<   |S )z9Returns a topic_subscription dict with additional fields.rW   rU   rT   )r   r   r;   r-   r   )topic_subscriptionr   r   s      r    ListTopicSubscriptionDisplayDictr   D  sO    ..)*,& ''9:(33&-==&		-r   c                     t        j                  |       }t        | j                        }|j                  |d<   |j
                  |d<   t        | j                        }|j                  |d<   | j                  |d<   |S )z/Returns a snapshot dict with additional fields.rU   r   rZ   r   )
r   r   r7   rM   r-   snapshotsIdr?   r[   r   r   )rQ   r   snapshot_refr   s       r   ListSnapshotDisplayDictr   O  ss    ..x8&x}}-,$//&%11&()((&!,,&	-r   c                  j    t         j                  j                  j                  j	                  d      S )zReturns the value of the core/project config property.

  Config properties can be overridden with command line flags. If the --project
  flag was provided, this will return the value provided with the flag.
  TrE   rG   r   r   r   
GetProjectr   [  s*     
					'	'	+	+T	+	::r   c                 n    t         j                  j                  | dt        id      j	                         S )zParses a schema name using configuration properties for fallback.

  Args:
    schema: str, the schema's ID, fully-qualified URL, or relative name

  Returns:
    str: the relative name of the schema resource
  r-   r   r.   )r   r2   r3   r   RelativeName)schemas    r   ParseSchemaNamer   d  s;     
			!	!

- 
" 
/ 0<|~>r   c                 B    t         j                  j                  d       y)z1Logs a message indicating that a schema is valid.zSchema is valid.Nr
   statusPrintunused_responseunused_argss     r   OutputSchemaValidatedr   s  s    **%&r   c                 B    t         j                  j                  d       y)z2Logs a message indicating that a message is valid.zMessage is valid.Nr   r   s     r   OutputMessageValidatedr   x  s    **&'r   c                 j    | D cg c]  }|d   	 }}|D cg c]	  }||vs| }}||fS c c}w c c}w )NAckIdr   )ack_ids_and_failure_reasonsack_idsackfailed_ack_idsack_idsuccessfully_processed_ack_idss         r   'ParseExactlyOnceAckIdsAndFailureReasonsr   }  sX    ,GH,GSCL,G.H"$"fN&Bf7 ! $ 
7	77	 I$s   +	00c                 v    t        j                  |       }t        |j                  j                        }|s| |S r'   )excHttpExceptionParseExactlyOnceErrorInfopayloaddetails)errorer   s      r   HandleExactlyOnceDeliveryErrorr     s7    	! 9!)):K:K L 
%
K	$$r   c                    g }| D ]z  }d|vsd|d   vrd|vst        |d   t              s'|d   j                         D ]>  \  }}d|v sd|v st        j                  i       }||d<   ||d<   |j                  |       @ | |S )zParses error metadata for exactly once ack/modAck failures.

  Args:
    error_metadata: error metadata as dict of format ack_id -> failure_reason.

  Returns:
    list: error metadata with only exactly once failures.
  reasonEXACTLY_ONCEmetadataPERMANENT_FAILURETEMPORARY_FAILUREr   FailureReason)rN   rO   itemsr   r   r   )error_metadatar   error_mdr   failure_reasonr   s         r   r   r     s     !# hx>(9K#K!HZ4H$)O"*:"6"<"<">		.3F6D4E#44R8 w"0#**62 #? ! 
%$r   )zInternal Error)r   r'   )Er   
__future__r   r   r   googlecloudsdk.api_lib.pubsubr   r   googlecloudsdk.api_lib.utilr   r   #googlecloudsdk.command_lib.projectsr	   rA   googlecloudsdk.corer
   r   r   googlecloudsdk.core.resourcer   googlecloudsdk.core.utilr   r   r   r=   TOPICS_PUBLISH_COLLECTIONr4   SNAPSHOTS_LIST_COLLECTIONr9   SUBSCRIPTIONS_ACK_COLLECTIONSUBSCRIPTIONS_LIST_COLLECTION SUBSCRIPTIONS_MOD_ACK_COLLECTION#SUBSCRIPTIONS_MOD_CONFIG_COLLECTIONSUBSCRIPTIONS_PULL_COLLECTIONSUBSCRIPTIONS_SEEK_COLLECTIONSCHEMAS_COLLECTIONrl   rk   Errorr   r   r*   r7   r;   r?   rB   r1   rR   rX   r\   ry   rm   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      sT    @ &  ' 7 0 9 E * # * ) ; * 
 +  - 3 2 3 : 9  ; #A  &G # ;  ; . 6 2	; 7-:++ -9*** 9 '7CCG@0
I(	5%/Nd1L', 8"		;>'
(
8%%r   