
    	]j\                        d Z ddlmZmZ ddlmZmZ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mZmZmZmZmZmZmZ ddlmZ  G d de      Z  G d de      Z! G d de      Z"d Z#d Z$d Z%d Z&d Z'd Z(y)zOWrapper for adapting the autogenerated gapic client to the hand-written
client.    )client_infogapic_v1)MessageToDict	ParseDict
ParseError)entry_from_resource)Metric)ConfigServiceV2Client)LoggingServiceV2Client)MetricsServiceV2Client)Sink)CreateSinkRequestListLogEntriesRequestListLogMetricsRequestListSinksRequest	LogMetricLogSinkUpdateSinkRequestWriteLogEntriesRequest)LogEntryc                   D    e Zd ZdZd ZdddddddZddddddd	Zd
 Zy)_LoggingAPIz$Helper mapping logging-related APIs.c                      || _         || _        y N
_gapic_api_clientself	gapic_apiclients      H/root/env/lib/python3.12/site-packages/google/cloud/logging_v2/_gapic.py__init__z_LoggingAPI.__init__+       #    N)filter_order_bymax_results	page_size
page_tokenc                     |}t        |||||      } j                  j                  |      }t        |      }	i dk  rt	        d       fd}
 |
|	      S )a(  Return a generator of log entry resources.

        Args:
            resource_names (Sequence[str]): Names of one or more parent resources
                from which to retrieve log entries:

                ::

                    "projects/[PROJECT_ID]"
                    "organizations/[ORGANIZATION_ID]"
                    "billingAccounts/[BILLING_ACCOUNT_ID]"
                    "folders/[FOLDER_ID]"

            filter_ (str): a filter expression. See
                https://cloud.google.com/logging/docs/view/advanced_filters
            order_by (str) One of :data:`~logging_v2.ASCENDING`
                or :data:`~logging_v2.DESCENDING`.
            max_results (Optional[int]):
                Optional. The maximum number of entries to return.
                Non-positive values are treated as 0. If None, uses API defaults.
            page_size (int): number of entries to fetch in each API call. Although
                requests are paged internally, logs are returned by the generator
                one at a time. If not passed, defaults to a value set by the API.
            page_token (str): opaque marker for the starting "page" of entries. If not
                passed, the API will return the first page of entries.
        Returns:
            Generator[~logging_v2.LogEntry]
        )resource_namesfilterr'   r)   r*   requestr   max_results must be positivec              3      K   d}| D ]H  }|k\  r y t        t        j                  |            }t        |j                         |dz  }J y w)Nr   )loggers   )_parse_log_entry
LogEntryPBpbr   r   )log_iterientrylog_entry_dictr2   r(   r   s       r"   log_entries_pagerz3_LoggingAPI.list_entries.<locals>.log_entries_pagerk   s[     A! *qK/?!1*--2F!G).$,,PWXXQs   AA)r   r   list_log_entriesiter
ValueError)r   r,   r&   r'   r(   r)   r*   r/   responser7   r;   r2   s   `   `      @r"   list_entriesz_LoggingAPI.list_entries/   sw    N (')!
 ??33G3D>
 "{Q;<<	 !**r%   TF)logger_nameresourcelabelspartial_successdry_runc                    	 |D cg c]  }t        |       }}t	        |||||      }
| j
                  j                  |
       yc c}w # t        $ r}	t        dt        |	             |	d}	~	ww xY w)a  Log an entry resource via a POST request

        Args:
            entries (Sequence[Mapping[str, ...]]): sequence of mappings representing
                the log entry resources to log.
            logger_name (Optional[str]): name of default logger to which to log the entries;
                individual entries may override.
            resource(Optional[Mapping[str, ...]]): default resource to associate with entries;
                individual entries may override.
            labels (Optional[Mapping[str, ...]]): default labels to associate with entries;
                individual entries may override.
            partial_success (Optional[bool]): Whether valid entries should be written even if
                some other entries fail due to INVALID_ARGUMENT or
                PERMISSION_DENIED errors. If any entry is not written, then
                the response status is the error associated with one of the
                failed entries and the response includes error details keyed
                by the entries' zero-based index in the ``entries.write``
                method.
            dry_run (Optional[bool]):
                If true, the request should expect normal response,
                but the entries won't be persisted nor exported.
                Useful for checking whether the logging API endpoints are working
                properly before sending valuable data.
        zInvalid log entry: N)log_namerB   rC   entriesrD   r.   )_log_entry_mapping_to_pbr   r>   strr   r   write_log_entries)r   rH   rA   rB   rC   rD   rE   r9   log_entry_pbser/   s              r"   write_entriesz_LoggingAPI.write_entriesv   s    D	DJQR5e<RMR ) !+
 	))'): S 	D23q6(;<!C	Ds'   A AA A 	A2A--A2c                 <    | j                   j                  |       y)aq  Delete all entries in a logger.

        Args:
            logger_name (str):  The resource name of the log to delete:

                ::

                    "projects/[PROJECT_ID]/logs/[LOG_ID]"
                    "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
                    "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
                    "folders/[FOLDER_ID]/logs/[LOG_ID]"

                ``[LOG_ID]`` must be URL-encoded. For example,
                ``"projects/my-project-id/logs/syslog"``,
                ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``.
        )rG   N)r   
delete_log)r   rA   s     r"   logger_deletez_LoggingAPI.logger_delete   s    " 	""K"8r%   )__name__
__module____qualname____doc__r#   r@   rN   rQ    r%   r"   r   r   (   s>    . E+V .;`9r%   r   c                   J    e Zd ZdZd ZdddddZdddZd	 Zddd
Zd Z	y)	_SinksAPI!Helper mapping sink-related APIs.c                      || _         || _        y r   r   r   s      r"   r#   z_SinksAPI.__init__   r$   r%   Nr(   r)   r*   c                     t        |||      } j                  j                  |      }t        |      }dk  rt	        d       fd} ||      S )a  List sinks for the parent resource.

        Args:
            parent (str): The parent resource whose sinks are to be listed:

                ::

                    "projects/[PROJECT_ID]"
                    "organizations/[ORGANIZATION_ID]"
                    "billingAccounts/[BILLING_ACCOUNT_ID]"
                    "folders/[FOLDER_ID]".
            max_results (Optional[int]):
                Optional. The maximum number of entries to return.
                Non-positive values are treated as 0. If None, uses API defaults.
            page_size (int): number of entries to fetch in each API call. Although
                requests are paged internally, logs are returned by the generator
                one at a time. If not passed, defaults to a value set by the API.
            page_token (str): opaque marker for the starting "page" of entries. If not
                passed, the API will return the first page of entries.

        Returns:
            Generator[~logging_v2.Sink]
        parentr)   r*   r   r0   c              3      K   d}| D ]F  }|k\  r y t        j                  t        j                  |      j                         |dz  }H y wNr   )r!   r3   )r   from_api_reprr   to_dictr   )	sink_iterr8   r9   r(   r   s      r"   sinks_pagerz)_SinksAPI.list_sinks.<locals>.sinks_pager   sT     A" *qK/?(()?UUQ   AA)r   r   
list_sinksr=   r>   )	r   r^   r(   r)   r*   r/   r?   rc   rd   s	   ` `      r"   rf   z_SinksAPI.list_sinks   s_    0 #Y:
 ??--g6N	"{Q;<<	 9%%r%   F)unique_writer_identityc                    t        |||      }t        |||      }| j                  j                  |      }t	        t        j
                  |      d      S )a  Create a sink resource.

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create

        Args:
            parent(str): The resource in which to create the sink,
                including the parent resource and the sink identifier:

            ::

                "projects/[PROJECT_ID]"
                "organizations/[ORGANIZATION_ID]"
                "billingAccounts/[BILLING_ACCOUNT_ID]"
                "folders/[FOLDER_ID]".
            sink_name (str): The name of the sink.
            filter_ (str): The advanced logs filter expression defining the
                entries exported by the sink.
            destination (str): Destination URI for the entries exported by
                the sink.
            unique_writer_identity (Optional[bool]):  determines the kind of
                IAM identity returned as writer_identity in the new sink.

        Returns:
            dict: The sink resource returned from the API (converted from a
                protobuf to a dictionary).
        namer-   destination)r^   sinkrg   r.   Fpreserving_proto_field_name)r   r   r   create_sinkr   r6   )	r   r^   	sink_namer&   rk   rg   sink_pbr/   
created_pbs	            r"   sink_createz_SinksAPI.sink_create   sY    < ykR#@V
 __000A
JJz"(-
 	
r%   c                 z    | j                   j                  |      }t        t        j                  |      d      S )aC  Retrieve a sink resource.

        Args:
            sink_name (str): The resource name of the sink,
                including the parent resource and the sink identifier:

            ::

                "projects/[PROJECT_ID]/sinks/[SINK_ID]"
                "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
                "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
                "folders/[FOLDER_ID]/sinks/[SINK_ID]"

        Returns:
            dict: The sink object returned from the API (converted from a
                protobuf to a dictionary).
        rp   Frm   )r   get_sinkr   r   r6   )r   rp   rq   s      r"   sink_getz_SinksAPI.sink_get  s9    $ //**Y*? JJw(-
 	
r%   c                    |j                  d      d   }t        |||      }t        |||      }| j                  j	                  |      }t        t        j                  |      d      S )a  Update a sink resource.

        Args:
            sink_name (str): Required. The resource name of the sink,
                including the parent resource and the sink identifier:

            ::

                "projects/[PROJECT_ID]/sinks/[SINK_ID]"
                "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
                "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
                "folders/[FOLDER_ID]/sinks/[SINK_ID]"
            filter_ (str): The advanced logs filter expression defining the
                entries exported by the sink.
            destination (str): destination URI for the entries exported by
                the sink.
            unique_writer_identity (Optional[bool]): determines the kind of
                IAM identity returned as writer_identity in the new sink.


        Returns:
            dict: The sink resource returned from the API (converted from a
                  protobuf to a dictionary).
        /ri   )rp   rl   rg   r.   Frm   )splitr   r   r   update_sinkr   r6   )r   rp   r&   rk   rg   rj   rq   r/   s           r"   sink_updatez_SinksAPI.sink_update/  sw    @ s#B'#
 $#9

 //--g-> JJw(-
 	
r%   c                 <    | j                   j                  |       y)a  Delete a sink resource.

        Args:
            sink_name (str): Required. The full resource name of the sink to delete,
            including the parent resource and the sink identifier:

            ::

                "projects/[PROJECT_ID]/sinks/[SINK_ID]"
                "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
                "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
                "folders/[FOLDER_ID]/sinks/[SINK_ID]"

            Example: ``"projects/my-project-id/sinks/my-sink-id"``.
        ru   N)r   delete_sink)r   rp   s     r"   sink_deletez_SinksAPI.sink_deletec  s      	##i#8r%   )
rR   rS   rT   rU   r#   rf   rs   rw   r}   r   rV   r%   r"   rX   rX      s=    + 15QU *&Z RW&
P
@  %2
h9r%   rX   c                   >    e Zd ZdZd ZdddddZd Zd Zd Zd	 Z	y)
_MetricsAPIrY   c                      || _         || _        y r   r   r   s      r"   r#   z_MetricsAPI.__init__y  r$   r%   Nr[   c                     d| }t        |||      } j                  j                  |      }t        |      }dk  rt	        d       fd}	 |	|      S )a,  List metrics for the project associated with this client.

        Args:
            project (str): ID of the project whose metrics are to be listed.
            max_results (Optional[int]):
                Optional. The maximum number of entries to return.
                Non-positive values are treated as 0. If None, uses API defaults.
            page_size (int): number of entries to fetch in each API call. Although
                requests are paged internally, logs are returned by the generator
                one at a time. If not passed, defaults to a value set by the API.
            page_token (str): opaque marker for the starting "page" of entries. If not
                passed, the API will return the first page of entries.

        Returns:
            Generator[logging_v2.Metric]
        	projects/r]   r.   r   r0   c              3      K   d}| D ]F  }|k\  r y t        j                  t        j                  |      j                         |dz  }H y wr`   )r	   ra   r   rb   r   )metric_iterr8   r9   r(   r   s      r"   metrics_pagerz/_MetricsAPI.list_metrics.<locals>.metrics_pager  s]     A$ *qK/?**%%e,T\\  Qre   )r   r   list_log_metricsr=   r>   )
r   projectr(   r)   r*   pathr/   r?   r   r   s
   ` `       r"   list_metricsz_MetricsAPI.list_metrics}  sp    & 7)$'!

 ??33G3D8n"{Q;<<		 [))r%   c                 d    d| }t        |||      }| j                  j                  ||       y)a  Create a metric resource.

        See
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create

        Args:
            project (str): ID of the project in which to create the metric.
            metric_name (str): The name of the metric
            filter_ (str): The advanced logs filter expression defining the
                entries exported by the metric.
            description (str): description of the metric.
        r   rj   r-   description)r^   metricN)r   r   create_log_metric)r   r   metric_namer&   r   r^   	metric_pbs          r"   metric_createz_MetricsAPI.metric_create  s5     WI&;wKX	))	)Jr%   c                     d| d| }| j                   j                  |      }t        t        j                  |      d      S )a8  Retrieve a metric resource.

        Args:
            project (str): ID of the project containing the metric.
            metric_name (str): The name of the metric

        Returns:
            dict: The metric object returned from the API (converted from a
                  protobuf to a dictionary).
        r   	/metrics/r   Frm   )r   get_log_metricr   r   r6   )r   r   r   r   r   s        r"   
metric_getz_MetricsAPI.metric_get  sK     7)9[M:OO22t2D	 LL#(-
 	
r%   c                     d| d| }t        |||      }| j                  j                  ||      }t        t        j                  |      d      S )a  Update a metric resource.

        Args:
            project (str): ID of the project containing the metric.
            metric_name (str): the name of the metric
            filter_ (str): the advanced logs filter expression defining the
                entries exported by the metric.
            description (str): description of the metric.

        Returns:
            The metric object returned from the API (converted from a
                  protobuf to a dictionary).
        r   r   r   )r   r   Frm   )r   r   update_log_metricr   r6   )r   r   r   r&   r   r   r   s          r"   metric_updatez_MetricsAPI.metric_update  sg    ( 7)9[M:#
	
 OO55Y 6 
	
 LL#(-
 	
r%   c                 L    d| d| }| j                   j                  |       y)zDelete a metric resource.

        Args:
            project (str): ID of the project containing the metric.
            metric_name (str): The name of the metric
        r   r   r   N)r   delete_log_metric)r   r   r   r   s       r"   metric_deletez_MetricsAPI.metric_delete  s+     7)9[M:))d);r%   )
rR   rS   rT   rU   r#   r   r   r   r   r   rV   r%   r"   r   r   v  s/    +
 '+dt**XK"
("
H<r%   r   c                     	 t        | d      S # t        $ rF | j                  d      r3| j                  }| j	                  d       t        | d      }||d<   |cY S  w xY w)a`  Special helper to parse ``LogEntry`` protobuf into a dictionary.

    The ``proto_payload`` field in ``LogEntry`` is of type ``Any``. This
    can be problematic if the type URL in the payload isn't in the
    ``google.protobuf`` registry. To help with parsing unregistered types,
    this function will remove ``proto_payload`` before parsing.

    Args:
        entry_pb (LogEntry): Log entry protobuf.

    Returns:
        dict: The parsed log entry. The ``protoPayload`` key may contain
              the raw ``Any`` protobuf from ``entry_pb.proto_payload`` if
              it could not be parsed.
    Frm   proto_payloadprotoPayload)r   	TypeErrorHasFieldr   
ClearField)entry_pbr   entry_mappings      r"   r4   r4     sw     (-
 	
  _-$22M0),1M -:M.)  s    AAAc                 j    t        j                  t                     }t        | |       t        |      S )zHelper for :meth:`write_entries`, et aliae

    Performs "impedance matching" between the protobuf attrs and
    the keys expected in the JSON API.
    )r5   r6   r   )mappingr   s     r"   rI   rI      s+     }}Z\*H gx hr%   c           	          t         j                  j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                        S )zg
    Helper function to convert api_core.client_info to
    api_core.gapic_v1.client_info subclass
    )python_versiongrpc_versionapi_core_versiongapic_versionclient_library_version
user_agentrest_version)
r   r   
ClientInfor   r   r   r   r   r   r   )
input_infos    r"   _client_info_to_gapicr   2  sa    
 **!00,,#44 ..)@@((,, +  r%   c                     | j                   }t        |t        j                        rt	        |      }t        | j                  || j                        }t        ||       S )zCreate an instance of the Logging API adapter.

    Args:
        client (~logging_v2.client.Client): The client
            that holds configuration details.

    Returns:
        _LoggingAPI: A metrics API instance with the proper credentials.
    credentialsr   client_options)	_client_info
isinstancer   r   r   r   _credentials_client_optionsr   r!   info	generateds      r"   make_logging_apir   B  W     D$../$T*&''--I
 y&))r%   c                     | j                   }t        |t        j                        rt	        |      }t        | j                  || j                        }t        ||       S )zCreate an instance of the Metrics API adapter.

    Args:
        client (~logging_v2.client.Client): The client
            that holds configuration details.

    Returns:
        _MetricsAPI: A metrics API instance with the proper credentials.
    r   )	r   r   r   r   r   r   r   r   r   r   s      r"   make_metrics_apir   Y  r   r%   c                     | j                   }t        |t        j                        rt	        |      }t        | j                  || j                        }t        ||       S )zCreate an instance of the Sinks API adapter.

    Args:
        client (~logging_v2.client.Client): The client
            that holds configuration details.

    Returns:
        _SinksAPI: A metrics API instance with the proper credentials.
    r   )	r   r   r   r   r   r
   r   r   rX   r   s      r"   make_sinks_apir   p  sW     D$../$T*%''--I
 Y''r%   N))rU   google.api_corer   r   google.protobuf.json_formatr   r   r    google.cloud.logging_v2._helpersr   google.cloud.logging_v2.metricr	   2google.cloud.logging_v2.services.config_service_v2r
   3google.cloud.logging_v2.services.logging_service_v2r   3google.cloud.logging_v2.services.metrics_service_v2r   google.cloud.logging_v2.sinkr   google.cloud.logging_v2.typesr   r   r   r   r   r   r   r   r   r5   objectr   rX   r   r4   rI   r   r   r   r   rV   r%   r"   <module>r      s    2 L L @ 1 T V V -	 	 	 AO9& O9dy9 y9xD<& D<N F $ *.*.(r%   