
    ;                        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 S\R4                  5      r " S S\5      rS rS rS rS rS r S r!S r"S3S jr#S r$S r%S r&S  r'S! r(S3S" jr)S3S# jr*S$ r+S% r,S& r-S' r.S( r/S) r0S* r1S+ r2 S4S- jr3 S4S. jr4S/ r5S0 r6S1 r7S5S2 jr8g,)6z3A library that is used to support logging commands.    )encoding)extra_types)folders)apis)arg_parsers)base)
completers)	arg_utils)common_args)
exceptions)log)
properties)	resources)yamlv2c                       \ rS rSrSrSrg)Error%   zBase error for this module. N__name__
__module____qualname____firstlineno____doc____static_attributes__r       *lib/googlecloudsdk/api_lib/logging/util.pyr   r   %   s    #r   r   c                       \ rS rSrSrSrg)InvalidJSONValueError)   zInvalid JSON value error.r   Nr   r   r   r   r    r    )   s    !r   r    c                  8    [         R                  " S[        5      $ )z'Returns the client for the logging API.logging)	core_apisGetClientInstanceDEFAULT_API_VERSIONr   r   r   	GetClientr'   -       		$	$Y0C	DDr   c                  8    [         R                  " S[        5      $ )z)Returns the messages for the logging API.r#   )r$   GetMessagesModuler&   r   r   r   GetMessagesr+   2   r(   r   c                      [         R                  R                  R                  R	                  SS9n [
        R                  R                  U SS9nUR                  5       $ )z:Returns the relative resource path to the current project.Trequiredcloudresourcemanager.projects
collection)	r   VALUEScoreprojectGetr   REGISTRYParseRelativeName)r4   project_refs     r   GetCurrentProjectParentr:   7   sY    ""**...='""((9 ) + 
	!	!	##r   c                     [         R                  R                  U [        U5      [	        U5      R                  5       0[        US5      S9$ )z4Returns the appropriate sink resource based on args.sinksparamsr1   )r   r6   r7   GetIdFromArgsGetParentResourceFromArgsNameGetCollectionFromArgs)	sink_nameargss     r   GetSinkReferencerE   @   sI    				!	!D!#<T#B#G#G#IJ&tW5 
" 
 r   c                     [         R                  R                  U [        U5      [	        U5      R                  5       SUR                  0[        US5      S9$ )z9Returns the appropriate operation resource based on args.locationsIdzlocations.operationsr=   )r   r6   r7   r?   r@   rA   locationrB   )operation_namerD   s     r   GetOperationReferencerJ   I   sW    				!	!

8>CCE
 't-CD 
" 
 r   c                 $    U R                  S5      $ )zReturns a string representing timestamp in RFC3339 format.

Args:
  timestamp: A datetime.datetime object.

Returns:
  A timestamp string in format, which is accepted by Cloud Logging.
z%Y-%m-%dT%H:%M:%S.%fZ)strftime)	timestamps    r   FormatTimestamprN   U   s     
		3	44r   c                 p     [         R                  " U 5      $ ! [         a  n[        SU-  5      eSnAff = f)z1Tries to convert the JSON string into JsonObject.zInvalid JSON value: %sN)r   JsonProtoDecoder	Exceptionr    )json_stringes     r   ConvertToJsonObjectrT   a   s9    >''44	 >
 81 <
==>s    
505c           	      z   U R                  5       nUR                  SSS[        R                  SR	                  U5      S9  UR                  SSSSR	                  U5      S	9  U(       d!  UR                  S
SSSR	                  U5      S	9  [
        R                  " SR	                  U5      S9R                  U5        g)zAdds arguments for parent of the entities.

Args:
  parser: parser to which arguments are added.
  help_string: text that is prepended to help for each argument.
  exclude_billing_account: whether to exclude the billing account argument.
z--organizationFORGANIZATION_IDzOrganization of the {0}.)r.   metavar	completerhelpz--folder	FOLDER_IDzFolder of the {0}.)r.   rW   rY   z--billing-accountBILLING_ACCOUNT_IDzBilling account of the {0}.zProject of the {0}.)help_text_to_prependN)add_mutually_exclusive_groupadd_argumentr	   OrganizationCompleterformatr   ProjectArgumentAddToParser)parserhelp_stringexclude_billing_accountentity_groups       r   AddParentArgsrg   i   s     446,00%,,[9   &&{3	   
!$*11+>	   077DKr   c           	      T    U R                  SUS[        R                  " SS5      US9  g)zAdds a location argument.

Args:
  parser: parser to which to add args.
  required: whether the arguments is required.
  help_string: the help string.
z
--locationLOCATIONz.+zmust be non-empty)r.   rW   typerY   N)r^   r   RegexpValidator)rc   r.   rd   s      r   AddBucketLocationArgrl      s4     	&&u.AB  r   c                     [         R                  R                  U =(       d1    [        R                  R
                  R                  R                  SS9SS9$ )z-Returns the resource for the current project.Tr-   r/   r0   )r   r6   r7   r   r2   r3   r4   r5   )r4   s    r   GetProjectResourcern      sK    				!	!B""''//33T3B0 
" 
 r   c                 >    [         R                  R                  U SS9$ )zjReturns the resource for the organization.

Args:
  organization: organization.

Returns:
  The resource.
z"cloudresourcemanager.organizationsr0   r   r6   r7   )organizations    r   GetOrganizationResourcerr      s(     
			!	!C 
" 
 r   c                 H    [         R                  " 5       R                  U SS9$ )zXReturns the resource for the folder.

Args:
  folder: folder.

Returns:
  The resource.
zcloudresourcemanager.foldersr0   )r   FoldersRegistryr7   )folders    r   GetFolderResourcerv      s+     
	 	 	"	(	(7 
) 
 r   c                 >    [         R                  R                  U SS9$ )zsReturns the resource for the billing_account.

Args:
  billing_account: billing account.

Returns:
  The resource.
zcloudbilling.billingAccountsr0   rp   )billing_accounts    r   GetBillingAccountResourcery      s(     
			!	!"@ 
" 
 r   c                    U R                   (       a  [        U R                   5      $ U R                  (       a  [        U R                  5      $ U(       d&  U R                  (       a  [        U R                  5      $ [        U R                  5      $ )zReturns the parent resource derived from the given args.

Args:
  args: command line args.
  exclude_billing_account: whether to exclude the billing account argument.

Returns:
  The parent resource.
)rq   rr   ru   rv   rx   ry   rn   r4   rD   re   s     r   r@   r@      s_     
"4#4#455{{T[[))"t';';$T%9%9::dll++r   c                 4    [        X5      R                  5       $ )zReturns the relative path to the parent from args.

Args:
  args: command line args.
  exclude_billing_account: whether to exclude the billing account argument.

Returns:
  The relative path. e.g. 'projects/foo', 'folders/1234'.
)r@   r8   r{   s     r   GetParentFromArgsr}      s     
#4	A	N	N	PPr   c                 n    U R                   (       a  U R                   nOSn[        [        U 5      SU5      $ )zReturns the relative path to the bucket location from args.

Args:
  args: command line args.

Returns:
  The relative path. e.g. 'projects/foo/locations/bar'.
-	locations)rH   CreateResourceNamer}   )rD   rH   s     r   GetBucketLocationFromArgsr      s.     
]]}}HH	-d3[(	KKr   c                 p    U R                   (       a  gU R                  (       a  gU R                  (       a  gg)z}Returns the id to be used for constructing resource paths.

Args:
  args: command line args.

Returns:
  The id to be used..
organizationsId	foldersIdbillingAccountsId
projectsId)rq   ru   rx   )rD   s    r   r?   r?     s)     
{{r   c                     U R                   (       a  SnO*U R                  (       a  SnOU R                  (       a  SnOSnSR                  X!5      $ )zReturns the collection derived from args and the suffix.

Args:
  args: command line args.
  collection_suffix: suffix of collection

Returns:
  The collection.
zlogging.organizationszlogging.folderszlogging.billingAccountszlogging.projectsz{0}.{1})rq   ru   rx   r`   )rD   collection_suffixprefixs      r   rB   rB     sB     
$F{{F&FF			&	44r   c                 F    SR                  XUR                  SS5      5      $ )aG  Creates the full resource name.

Args:
  parent: The project or organization id as a resource name, e.g.
    'projects/my-project' or 'organizations/123'.
  collection: The resource collection. e.g. 'logs'
  resource_id: The id within the collection , e.g. 'my-log'.

Returns:
  resource, e.g. projects/my-project/logs/my-log.
z{0}/{1}/{2}/%2F)r`   replace)parentr1   resource_ids      r   r   r   -  s)     
		+--c59
 r   c                 ,    SU;   a  U$ [        U SU5      $ )a  Creates the full log resource name.

Args:
  parent: The project or organization id as a resource name, e.g.
    'projects/my-project' or 'organizations/123'.
  log_id: The log id, e.g. 'my-log'. This may already be a resource name, in
    which case parent is ignored and log_id is returned directly, e.g.
    CreateLogResourceName('projects/ignored', 'projects/bar/logs/my-log')
    returns 'projects/bar/logs/my-log'

Returns:
  Log resource, e.g. projects/my-project/logs/my-log.
/logs/logs)r   )r   log_ids     r   CreateLogResourceNamer   A  s      M	FFF	33r   c                 P    U R                  SS5      S   nUR                  SS5      $ )zExtracts only the log id and restore original slashes.

Args:
  log_resource: The full log uri e.g projects/my-projects/logs/my-log.

Returns:
  A log id that can be used in other commands.
r      r   r   )splitr   )log_resourcer   s     r   ExtractLogIdr   T  s,     h*1-&	s	##r   c                 j    [         R                  " U [        5       R                  R                  SS/S9$ )a  Converts an Index Type String Literal to an Enum.

Args:
  index_type: The index type e.g INDEX_TYPE_STRING.

Returns:
  A IndexConfig.TypeValueValuesEnum mapped e.g
  TypeValueValuesEnum(INDEX_TYPE_INTEGER, 2) .

  Will return a Parser error if an incorrect value is provided.
INDEX_TYPE_STRINGINDEX_TYPE_INTEGER)valid_choices)r
   ChoiceToEnumr+   IndexConfigTypeValueValuesEnum)
index_types    r   IndexTypeToEnumr   a  s4     
		m33(*>?
 r   c                    U(       a  SR                  U5      nOSnU R                  S5      (       a/  [        R                  R	                  SR                  U5      5        OU R                  S5      (       a/  [        R                  R	                  SR                  U5      5        ODU R                  S5      (       a.  [        R                  R	                  SR                  U5      5        [        R                  R	                  S	5        g
)zPrints a message to remind the user to set up permissions for a sink.

Args:
  destination: the sink destination (either bigquery or cloud storage).
  writer_identity: identity to which to grant write access.
z`{0}`z!the group `cloud-logs@google.com`bigqueryzJPlease remember to grant {0} the BigQuery Data Editor role on the dataset.storagezKPlease remember to grant {0} the Storage Object Creator role on the bucket.pubsubzEPlease remember to grant {0} the Pub/Sub Publisher role on the topic.zjMore information about sinks can be found at https://cloud.google.com/logging/docs/export/configure_exportN)r`   
startswithsdk_logstatusPrint)destinationwriter_identitygrantees      r   PrintPermissionInstructionsr   t  s     nn_-G1GJ''NN	&&,fWo i((NN	&&,fWo h''NN	#VG_ 
..>r   Nc                     [        5       nU(       a>  [        R                  " U5      n[        R                  " XeR
                  5      nXl        U$ UR                  U UUUS9nU$ )a  Returns a LogMetric message based on a data stream or a description/filter.

Args:
  metric_name: str, the name of the metric.
  description: str, a description.
  log_filter: str, the filter for the metric's filter field.
  bucket_name: str, the bucket name which ownes the metric.
  data: str, a stream of data read from a config file.

Returns:
  LogMetric, the message representing the new metric.
)namedescriptionfilter
bucketName)r+   r   loadr   DictToMessage	LogMetricr   )metric_namer   
log_filterbucket_namedatamessagescontents
metric_msgs           r   CreateLogMetricr     si     ](	yyH''2D2DEJ!O 
 ##	 $ J 
r   c           	         [        5       nU(       a  Xl        U(       a  X l        U(       a  X0l        U(       aT  [        R
                  " U5      n[        R                  " XeR                  5      nU H  n[        X[        Xx5      5        M     U $ )a  Updates a LogMetric message given description, filter, and/or data.

Args:
  metric: LogMetric, the original metric.
  description: str, updated description if any.
  log_filter: str, updated filter for the metric's filter field if any.
  bucket_name: str, the bucket name which ownes the metric.
  data: str, a stream of data read from a config file if any.

Returns:
  LogMetric, the message representing the updated metric.
)r+   r   r   r   r   r   r   r   r   setattrgetattr)	metricr   r   r   r   r   update_datametric_diff
field_names	            r   UpdateLogMetricr     si     ]($M#	))D/K((6H6HIK!
f'+"BC "	-r   c                 v    [        5       R                  U S9n[        5       R                  R	                  U5      $ )z!Get IAM policy, for a given view.)resource)r+   7LoggingProjectsLocationsBucketsViewsGetIamPolicyRequestr'    projects_locations_buckets_viewsGetIamPolicy)viewget_iam_policy_requests     r   r   r     sB     mKK L  
 
	5	5	B	B
 r   c                     [        5       nUR                  U UR                  US9S9n[        5       R                  R                  U5      $ )z!Set IAM policy, for a given view.)policy)r   setIamPolicyRequest)r+   7LoggingProjectsLocationsBucketsViewsSetIamPolicyRequestSetIamPolicyRequestr'   r   SetIamPolicy)r   r   r   policy_requests       r   r   r     sX    ]( FF&::&:I G   
	5	5	B	B
 r   c            	          / SQn [         R                  " SS[        R                  " 5       [        R                  SR                  U 5      SS9$ )z(Makes the base.Argument for --tags flag.)z%List of tags KEY=VALUE pairs to bind.zEach item must be expressed asz4`<tag-key-namespaced-name>=<tag-value-short-name>`.
z?Example: `123/environment=production,123/costCenter=marketing`
z--tagsz	KEY=VALUE
T)rW   rj   actionrY   hidden)r   Argumentr   ArgDictUpdateActionjoin)
help_partss    r   
GetTagsArgr     sF    * 
 %%99Z 
 r   c                     [        X5      nU(       d  gU" [        UR                  5       5       VVs/ s H  u  pEUR                  XES9PM     snnS9$ s  snnf )zMakes the tags message object.N)keyvalue)additionalProperties)r   sorteditemsAdditionalProperty)rD   tags_messagetags_arg_nametagsr   r   s         r   GetTagsFromArgsr      s\    		%$		 #4::<00jc 
)
)c
)
?0
 s   A
)F)NNNN)r   )9r   apitools.base.pyr   r   'googlecloudsdk.api_lib.resource_managerr   googlecloudsdk.api_lib.utilr   r$   googlecloudsdk.callioper   r   +googlecloudsdk.command_lib.resource_managerr	   $googlecloudsdk.command_lib.util.apisr
   $googlecloudsdk.command_lib.util.argsr   googlecloudsdk.corer   r   r   r   r   r   r&   r   r    r'   r+   r:   rE   rJ   rN   rT   rg   rl   rn   rr   rv   ry   r@   r}   r   r?   rB   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s     : & ( ; 9 / ( B : < * . * ) $ $J $"E "E
E
$		5>!H(,(
QL"&5*(4&
$&D LP> GK>
$r   