
    ;                        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mZ ddlmZ ddlmZ ddlmZ dZ G d dej<                        Z G d de      Zd Z d Z!d Z"d Z#d Z$d Z%d Z&d6dZ'd  Z(d! Z)d" Z*d# Z+d$ Z,d6d%Z-d6d&Z.d' Z/d( Z0d) Z1d* Z2d+ Z3d, Z4d- Z5d. Z6	 d7d0Z7	 d7d1Z8d2 Z9d3 Z:d4 Z;d8d5Z<y/)9z3A library that is used to support logging commands.    )absolute_import)division)unicode_literals)encoding)extra_types)folders)apis)arg_parsers)base)
completers)	arg_utils)common_args)
exceptions)log)
properties)	resources)yamlv2c                       e Zd ZdZy)ErrorzBase error for this module.N__name__
__module____qualname____doc__     *lib/googlecloudsdk/api_lib/logging/util.pyr   r   (   s    #r   r   c                       e Zd ZdZy)InvalidJSONValueErrorzInvalid JSON value error.Nr   r   r   r   r    r    ,   s    !r   r    c                  6    t        j                  dt              S )z'Returns the client for the logging API.logging)	core_apisGetClientInstanceDEFAULT_API_VERSIONr   r   r   	GetClientr&   0       		$	$Y0C	DDr   c                  6    t        j                  dt              S )z)Returns the messages for the logging API.r"   )r#   GetMessagesModuler%   r   r   r   GetMessagesr*   5   r'   r   c                      t         j                  j                  j                  j	                  d      } t
        j                  j                  | d      }|j                         S )z:Returns the relative resource path to the current project.Trequiredcloudresourcemanager.projects
collection)	r   VALUEScoreprojectGetr   REGISTRYParseRelativeName)r3   project_refs     r   GetCurrentProjectParentr9   :   sY    ""**...='""((9 ) + 
	!	!	##r   c                     t         j                  j                  | t        |      t	        |      j                         it        |d            S )z4Returns the appropriate sink resource based on args.sinksparamsr0   )r   r5   r6   GetIdFromArgsGetParentResourceFromArgsNameGetCollectionFromArgs)	sink_nameargss     r   GetSinkReferencerD   C   sI    				!	!D!#<T#B#G#G#IJ&tW5 
" 
 r   c                     t         j                  j                  | t        |      t	        |      j                         d|j                  it        |d            S )z9Returns the appropriate operation resource based on args.locationsIdzlocations.operationsr<   )r   r5   r6   r>   r?   r@   locationrA   )operation_namerC   s     r   GetOperationReferencerI   L   sW    				!	!

8>CCE
 't-CD 
" 
 r   c                 $    | j                  d      S )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   FormatTimestamprM   X   s     
		3	44r   c                 l    	 t        j                  |       S # t        $ r}t        d|z        d}~ww xY w)z1Tries to convert the JSON string into JsonObject.zInvalid JSON value: %sN)r   JsonProtoDecoder	Exceptionr    )json_stringes     r   ConvertToJsonObjectrS   d   s9    >''44	 >
 81 <
==>s    	3.3c           	         | j                         }|j                  dddt        j                  dj	                  |             |j                  ddddj	                  |      	       |s$|j                  d
dddj	                  |      	       t        j                  dj	                  |            j                  |       y)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-   rV   rX   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   AddParentArgsrf   l   s     446,00%,,[9   &&{3	   
!$*11+>	   077DKr   c           	      X    | j                  d|dt        j                  dd      |       y)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-   rV   typerX   N)r]   r
   RegexpValidator)rb   r-   rc   s      r   AddBucketLocationArgrk      s4     	&&u.AB  r   c                     t         j                  j                  | xs4 t        j                  j
                  j                  j                  d      d      S )z-Returns the resource for the current project.Tr,   r.   r/   )r   r5   r6   r   r1   r2   r3   r4   )r3   s    r   GetProjectResourcerm      sK    				!	!B""''//33T3B0 
" 
 r   c                 D    t         j                  j                  | d      S )ztReturns the resource for the organization.

  Args:
    organization: organization.

  Returns:
    The resource.
  z"cloudresourcemanager.organizationsr/   r   r5   r6   )organizations    r   GetOrganizationResourcerq      s(     
			!	!C 
" 
 r   c                 L    t        j                         j                  | d      S )zbReturns the resource for the folder.

  Args:
    folder: folder.

  Returns:
    The resource.
  zcloudresourcemanager.foldersr/   )r   FoldersRegistryr6   )folders    r   GetFolderResourceru      s+     
	 	 	"	(	(7 
) 
 r   c                 D    t         j                  j                  | d      S )z}Returns the resource for the billing_account.

  Args:
    billing_account: billing account.

  Returns:
    The resource.
  zcloudbilling.billingAccountsr/   ro   )billing_accounts    r   GetBillingAccountResourcerx      s(     
			!	!"@ 
" 
 r   c                     | j                   rt        | j                         S | j                  rt        | j                        S |s!| j                  rt        | j                        S t        | j                        S )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.
  )rp   rq   rt   ru   rw   rx   rm   r3   rC   rd   s     r   r?   r?      s_     
"4#4#455{{T[[))"t';';$T%9%9::dll++r   c                 6    t        | |      j                         S )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?   r7   rz   s     r   GetParentFromArgsr|      s     
#4)@	A	N	N	PPr   c                 d    | j                   r| j                   }nd}t        t        |       d|      S )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)rG   CreateResourceNamer|   )rC   rG   s     r   GetBucketLocationFromArgsr      s.     
]]}}HH	-d3[(	KKr   c                 R    | j                   ry| j                  ry| j                  ryy)zReturns the id to be used for constructing resource paths.

  Args:
    args: command line args.

  Returns:
    The id to be used..
  organizationsId	foldersIdbillingAccountsId
projectsId)rp   rt   rw   )rC   s    r   r>   r>     s)     
{{r   c                     | j                   rd}n | j                  rd}n| j                  rd}nd}dj                  ||      S )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})rp   rt   rw   r_   )rC   collection_suffixprefixs      r   rA   rA     sE     
$F{{F&FF			&"3	44r   c                 H    dj                  | ||j                  dd            S )aW  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)parentr0   resource_ids      r   r   r   0  s+     
		j+--c59
 r   c                 (    d|v r|S t        | d|      S )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   D  s      M	FFF	33r   c                 P    | j                  dd      d   }|j                  dd      S )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   W  s,     h*1-&	s	##r   c                 n    t        j                  | t               j                  j                  ddg      S )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   d  s4     
		m33(*>?
 r   c                    |rdj                  |      }nd}| j                  d      r/t        j                  j	                  dj                  |             n| j                  d      r/t        j                  j	                  dj                  |             n?| j                  d      r.t        j                  j	                  dj                  |             t        j                  j	                  d	       y
)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   w  s     nn_-G1GJ'NN	&&,fWo i(NN	&&,fWo h'NN	#VG_ 
..>r   Nc                     t               }|r>t        j                  |      }t        j                  ||j
                        }| |_        |S |j                  | |||      }|S )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     sm     ](	yyH''(2D2DEJ!JO 
 ##	 $ J 
r   c           	          t               }|r|| _        |r|| _        |r|| _        |rSt	        j
                  |      }t        j                  ||j                        }|D ]  }t        | |t        ||              | S )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     su     ]($FFM#F	))D/K((h6H6HIK!
fj'+z"BC "	-r   c                 |    t               j                  |       }t               j                  j	                  |      S )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                     t               }|j                  | |j                  |            }t               j                  j                  |      S )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            	          g d} t        j                  ddt        j                         t        j                  dj                  |       d      S )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)rV   ri   actionrX   hidden)r   Argumentr
   ArgDictUpdateActionjoin)
help_partss    r   
GetTagsArgr     sF    * 
 %%99Z 
 r   c           
          t        | |      }|sy |t        |j                               D cg c]  \  }}|j                  ||       c}}      S c c}}w )zMakes the tags message object.N)keyvalue)additionalProperties)r   sorteditemsAdditionalProperty)rC   tags_messagetags_arg_nametagsr   r   s         r   GetTagsFromArgsr     sb    	}	%$		 #4::<00jc5 
)
)c
)
?0
 s   A
)F)NNNN)r   )=r   
__future__r   r   r   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*   r9   rD   rI   rM   rS   rf   rk   rm   rq   ru   rx   r?   r|   r   r>   rA   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   