diff --git a/.coveragerc b/.coveragerc index dd39c854..b16f6fc2 100644 --- a/.coveragerc +++ b/.coveragerc @@ -14,22 +14,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Generated by synthtool. DO NOT EDIT! [run] branch = True [report] fail_under = 100 show_missing = True +omit = google/cloud/devtools/cloudtrace/__init__.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore abstract methods - raise NotImplementedError -omit = - */gapic/*.py - */proto/*.py - */core/*.py - */site-packages/*.py \ No newline at end of file + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound \ No newline at end of file diff --git a/PUBLISHING.rst b/PUBLISHING.rst deleted file mode 100644 index a6d81225..00000000 --- a/PUBLISHING.rst +++ /dev/null @@ -1,46 +0,0 @@ -PUBLISHING ----------- - -Note: This folder has been generated by the GAPIC code generator. - -The instructions assumes that no changes have been made to folder and its -contents since it was created. - -PREREQUISITES -------------- - -- Python must installed -- [tox](https://testrun.org/tox/latest/) must be installed - - -TO PUBLISH ----------- - -- Make sure you have `an account`_ on pypi_. -- Publish your package using tox. -- *tox must be used here or the uploaded package will be invalid!!* - - :: - - tox -e upload-package - - -TO PUBLISH THE DOCS -------------------- - -- Create the docs - - :: - - tox -e docs - -- Publish them to pythonhosted.org - - :: - - tox -e upload-docs - - -_`Packaging and Distributing projects`: https://packaging.python.org/en/latest/distributing.html#uploading-your-project-to-pypi -_`an account`: https://pypi.python.org/pypi?%3Aaction=register_form -_pypi: http://pypi.python.org diff --git a/README.rst b/README.rst index 71642c97..d60b8671 100644 --- a/README.rst +++ b/README.rst @@ -56,7 +56,9 @@ Python >= 3.5 Deprecated Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^ -Python == 2.7. Python 2.7 support will be removed on January 1, 2020. +Python == 2.7. + +The last version of this library compatible with Python 2.7 is google-cloud-trace==0.24.0 Mac/Linux @@ -87,22 +89,6 @@ to `Python Development Environment Setup Guide`_ for Google Cloud Platform. .. _Python Development Environment Setup Guide: https://cloud.google.com/python/setup -Example Usage -~~~~~~~~~~~~~ - -.. code-block:: python - - from google.cloud.trace import trace_service_client - - client = trace_service_client.TraceServiceClient() - project_id = 'your-project-123' - - # Iterate over all results - for element in client.list_traces(project_id): - # process element - pass - - Next Steps ~~~~~~~~~~ diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 00000000..b6bcca24 --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,162 @@ +# 1.0.0 Migration Guide + +The 1.0 release of the `google-cloud-trace` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. + +If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-trace/issues). + +## Supported Python Versions + +> **WARNING**: Breaking change + +The 1.0.0 release requires Python 3.6+. + + +## Handwritten Client Wrapper Removal + +The handwritten client wrapper `trace_v1.Client()` and `trace_v2.Client()` have been removed. Please use `TraceServiceClient` directly. The primary diference is that a `project_id` must always be supplied to method calls. + + +```py +from google.cloud import trace_v1 + +client = trace_v1.TraceServiceClient() +``` + +```py +from google.cloud import trace_v2 + +client = trace_v2.TraceServiceClient() +``` + +**NOTE**: The following sections identify changes between the previous `TraceServiceClient()` and the current `TraceServiceClient()` (not the handwritten wrapper `Client()`). If you were previously using `Client()`, it may be more helpful to reference the [samples](https://github.com/googleapis/python-trace/tree/master/samples/snippets). + +## Method Calls + +> **WARNING**: Breaking change +Methods expect request objects. We provide a script that will convert most common use cases. + +* Install the library + +```py +python3 -m pip install google-cloud-trace +``` + +* The scripts `fixup_trace_v1_keywords.py` and `fixup_trace_v2_keywords.py` are shipped with the library. The script expects +an input directory (with the code to convert) and an empty destination directory. + +```sh +$ fixup_trace_v1_keywords.py --input-directory .samples/ --output-directory samples/ +``` + +**Before:** +```py +from google.cloud import trace_v1 + +client = trace_v1.TraceServiceClient() +project_id = "my-project" +response = client.list_traces(project_id) +``` + + +**After:** +```py +from google.cloud import trace_v1 + +client = trace_v1.TraceServiceClient() +project_id = "my-project" +response = client.list_traces(project_id=project_id) +``` + +### More Details + +In `google-cloud-trace<1.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. + +**Before:** +```py + def get_trace( + self, + project_id, + trace_id, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): +``` + +In the 1.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. + +Some methods have additional keyword only parameters. The available parameters depend on the [`google.api.method_signature` annotation](https://github.com/googleapis/googleapis/blob/master/google/devtools/cloudtrace/v2/tracing.proto#L53) specified by the API producer. + + +**After:** +```py + def get_trace( + self, + request: trace.GetTraceRequest = None, + *, + project_id: str = None, + trace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trace.Trace: +``` + +> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. +> Passing both will result in an error. + + +Both of these calls are valid: + +```py +response = client.get_trace( + request={ + "project_id": project_id, + "trace_id", trace_id, + } +) +``` + +```py +response = client.get_trace( + project_id=project_id, + trace_id=trace_id, +) +``` + +This call is invalid because it mixes `request` with a keyword argument `trace_id`. Executing this code +will result in an error. + +```py +response = client.get_trace( + request={ + "project_id": project_id, + }, + trace_id=trace_id, +) +``` + + + +## Enums and Types + + +**WARNING**: Breaking change + +The submodules `types` is no longer available on the unversioned path `trace`. + +**Before:** +```py +from google.cloud import trace + +trace_ = trace.types.TraceSpan() +``` + + +**After:** +```py +from google.cloud + +trace_ = trace_v1.TraceSpan() +trace_ = trace_v1.types.TraceSpan() +``` \ No newline at end of file diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index 2de320c9..00000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Stackdriver Trace API -================================ - -.. automodule:: google.cloud.trace_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index e2c1a9b9..00000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Stackdriver Trace API Client -====================================== - -.. automodule:: google.cloud.trace_v1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v2/api.rst b/docs/gapic/v2/api.rst deleted file mode 100644 index 48f0d58d..00000000 --- a/docs/gapic/v2/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Stackdriver Trace API -================================ - -.. automodule:: google.cloud.trace_v2 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v2/types.rst b/docs/gapic/v2/types.rst deleted file mode 100644 index 071d7a5a..00000000 --- a/docs/gapic/v2/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Stackdriver Trace API Client -====================================== - -.. automodule:: google.cloud.trace_v2.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index fe63ccf4..d3130000 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -10,18 +10,17 @@ The current version of the API is ``v2``: .. toctree:: :maxdepth: 2 - gapic/v2/api - gapic/v2/types + trace_v2/services + trace_v2/types Support for the previous API release, ``v1``, is provided for code previously -written against it. In order to use this release, you will want to import from -e.g. ``google.cloud.trace_v1`` in lieu of ``google.cloud.trace_v2``. +written against it. .. toctree:: :maxdepth: 2 - gapic/v1/api - gapic/v1/types + trace_v1/services + trace_v1/types Changelog diff --git a/docs/trace_v1/services.rst b/docs/trace_v1/services.rst new file mode 100644 index 00000000..e900d74b --- /dev/null +++ b/docs/trace_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Trace v1 API +====================================== + +.. automodule:: google.cloud.trace_v1.services.trace_service + :members: + :inherited-members: diff --git a/docs/trace_v1/types.rst b/docs/trace_v1/types.rst new file mode 100644 index 00000000..3055682c --- /dev/null +++ b/docs/trace_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Trace v1 API +=================================== + +.. automodule:: google.cloud.trace_v1.types + :members: diff --git a/docs/trace_v2/services.rst b/docs/trace_v2/services.rst new file mode 100644 index 00000000..ce3705dd --- /dev/null +++ b/docs/trace_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Trace v2 API +====================================== + +.. automodule:: google.cloud.trace_v2.services.trace_service + :members: + :inherited-members: diff --git a/docs/trace_v2/types.rst b/docs/trace_v2/types.rst new file mode 100644 index 00000000..b5e205ce --- /dev/null +++ b/docs/trace_v2/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Trace v2 API +=================================== + +.. automodule:: google.cloud.trace_v2.types + :members: diff --git a/google/__init__.py b/google/__init__.py deleted file mode 100644 index 5284146e..00000000 --- a/google/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__import__("pkg_resources").declare_namespace(__name__) diff --git a/google/cloud/__init__.py b/google/cloud/__init__.py deleted file mode 100644 index 5284146e..00000000 --- a/google/cloud/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__import__("pkg_resources").declare_namespace(__name__) diff --git a/google/cloud/trace/__init__.py b/google/cloud/trace/__init__.py index 697ae167..cf1a5c18 100644 --- a/google/cloud/trace/__init__.py +++ b/google/cloud/trace/__init__.py @@ -1,4 +1,6 @@ -# Copyright 2017 Google LLC +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,24 +13,26 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -from __future__ import absolute_import - -from pkg_resources import get_distribution - -__version__ = get_distribution("google-cloud-trace").version - -from google.cloud.trace.client import Client -from google.cloud.trace_v2 import types -from google.cloud.trace_v2.gapic import enums -from google.cloud.trace_v2.gapic import trace_service_client - - -class TraceServiceClient(trace_service_client.TraceServiceClient): - __doc__ = trace_service_client.TraceServiceClient.__doc__ - enums = enums - - -__all__ = ("__version__", "enums", "types", "TraceServiceClient", "Client", "SCOPE") - -SCOPE = Client.SCOPE +from google.cloud.trace_v2.services.trace_service.async_client import ( + TraceServiceAsyncClient, +) +from google.cloud.trace_v2.services.trace_service.client import TraceServiceClient +from google.cloud.trace_v2.types.trace import AttributeValue +from google.cloud.trace_v2.types.trace import Module +from google.cloud.trace_v2.types.trace import Span +from google.cloud.trace_v2.types.trace import StackTrace +from google.cloud.trace_v2.types.trace import TruncatableString +from google.cloud.trace_v2.types.tracing import BatchWriteSpansRequest + +__all__ = ( + "AttributeValue", + "BatchWriteSpansRequest", + "Module", + "Span", + "StackTrace", + "TraceServiceAsyncClient", + "TraceServiceClient", + "TruncatableString", +) diff --git a/google/cloud/trace/_gapic.py b/google/cloud/trace/_gapic.py deleted file mode 100644 index 00ac94d3..00000000 --- a/google/cloud/trace/_gapic.py +++ /dev/null @@ -1,321 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrapper for interacting with the Stackdriver Trace API.""" - -from google.api_core.gapic_v1 import method -from google.cloud._helpers import _datetime_to_pb_timestamp -from google.cloud.trace_v2.gapic import trace_service_client -from google.cloud.trace_v2.proto import trace_pb2 -from google.protobuf.json_format import ParseDict -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 - - -class _TraceAPI(object): - """ - Wrapper to help mapping trace-related APIs. - - See - https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools. - cloudtrace.v2 - - Args: - gapic (~google.cloud.trace_v2.gapic.trace_service_client. - TraceServiceClient): Required. API object used to make RPCs. - - client (~google.cloud.trace_v2.client.Client): Required. The - client that owns this API object. - """ - - def __init__(self, gapic_api, client): - self._gapic_api = gapic_api - self.client = client - - def batch_write_spans( - self, name, spans, retry=method.DEFAULT, timeout=method.DEFAULT - ): - """ - Sends new spans to Stackdriver Trace or updates existing traces. If the - name of a trace that you send matches that of an existing trace, new - spans are added to the existing trace. Attempt to update existing spans - results undefined behavior. If the name does not match, a new trace is - created with given set of spans. - - Args: - name (str): Required. Name of the project where the spans belong. - The format is ``projects/PROJECT_ID``. - spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): A - collection of spans. If a dict is provided, it must be of the - same form as the protobuf message - :class:`~google.cloud.trace_v2.types.Span` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will not - be retried. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - spans_pb_list = [] - - for span_mapping in spans["spans"]: - span_pb = _dict_mapping_to_pb(span_mapping, "Span") - spans_pb_list.append(span_pb) - - self._gapic_api.batch_write_spans( - name=name, spans=spans_pb_list, retry=retry, timeout=timeout - ) - - def create_span( - self, - name, - span_id, - display_name, - start_time, - end_time, - parent_span_id=None, - attributes=None, - stack_trace=None, - time_events=None, - links=None, - status=None, - same_process_as_parent_span=None, - child_span_count=None, - retry=method.DEFAULT, - timeout=method.DEFAULT, - ): - """ - Creates a new Span. - - Example: - >>> from google.cloud import trace_v2 - >>> - >>> client = trace_v2.TraceServiceClient() - >>> - >>> name = client.span_path('[PROJECT]', '[TRACE]', '[SPAN]') - >>> span_id = '' - >>> display_name = {} - >>> start_time = {} - >>> end_time = {} - >>> - >>> response = client.create_span(name, span_id, display_name, - start_time, end_time) - - Args: - name (str): The resource name of the span in the following format: - - :: - - projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] - - [TRACE_ID] is a unique identifier for a trace within a project. - [SPAN_ID] is a unique identifier for a span within a trace, - assigned when the span is created. - span_id (str): The [SPAN_ID] portion of the span's resource name. - The ID is a 16-character hexadecimal encoding of an 8-byte - array. - display_name (dict): A description of the span's operation - (up to 128 bytes). Stackdriver Trace displays the description - in the {% dynamic print site_values.console_name %}. - For example, the display name can be a qualified method name - or a file name and a line number where the operation is called. - A best practice is to use the same display name within an - application and at the same call point. This makes it easier to - correlate spans in different traces. - Contains two fields, value is the truncated name, - truncatedByteCount is the number of bytes removed from the - original string. If 0, then the string was not shortened. - start_time (:class:`~datetime.datetime`): - The start time of the span. On the client side, this is the - time kept by the local machine where the span execution starts. - On the server side, this is the time when the server's - application handler starts running. - end_time (:class:`~datetime.datetime`): - The end time of the span. On the client side, this is the time - kept by the local machine where the span execution ends. On the - server side, this is the time when the server application - handler stops running. - parent_span_id (str): The [SPAN_ID] of this span's parent span. - If this is a root span, then this field must be empty. - attributes (dict): A set of attributes on the span. There is a - limit of 32 attributes per span. - stack_trace (dict): - Stack trace captured at the start of the span. - Contains two fields, stackFrames is a list of stack frames in - this call stack, a maximum of 128 frames are allowed per - StackFrame; stackTraceHashId is used to conserve network - bandwidth for duplicate stack traces within a single trace. - time_events (dict): - The included time events. There can be up to 32 annotations - and 128 message events per span. - links (dict): A maximum of 128 links are allowed per Span. - status (dict): An optional final status for this span. - same_process_as_parent_span (bool): A highly recommended but not - required flag that identifies when a trace crosses a process - boundary. True when the parent_span belongs to the same process - as the current span. - child_span_count (int): An optional number of child spans that were - generated while this span was active. If set, allows - implementation to detect missing child spans. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will not - be retried. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - - Returns: - A :class:`~google.cloud.trace_v2.types.Span` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Convert the dict type parameters to protobuf - display_name = _dict_mapping_to_pb(display_name, "TruncatableString") - start_time = _datetime_to_pb_timestamp(start_time) - end_time = _datetime_to_pb_timestamp(end_time) - - if attributes is not None: - attributes = _span_attrs_to_pb(attributes, "Attributes") - - if stack_trace is not None: - stack_trace = _dict_mapping_to_pb(stack_trace, "StackTrace") - - if time_events is not None: - time_events = _span_attrs_to_pb(time_events, "TimeEvents") - - if links is not None: - links = _span_attrs_to_pb(links, "Links") - - if status is not None: - status = _status_mapping_to_pb(status) - - if same_process_as_parent_span is not None: - same_process_as_parent_span = _value_to_pb( - same_process_as_parent_span, "BoolValue" - ) - - if child_span_count is not None: - child_span_count = _value_to_pb(child_span_count, "Int32Value") - - return self._gapic_api.create_span( - name=name, - span_id=span_id, - display_name=display_name, - start_time=start_time, - end_time=end_time, - parent_span_id=parent_span_id, - attributes=attributes, - stack_trace=stack_trace, - time_events=time_events, - links=links, - status=status, - same_process_as_parent_span=same_process_as_parent_span, - child_span_count=child_span_count, - ) - - -def _dict_mapping_to_pb(mapping, proto_type): - """ - Convert a dict to protobuf. - - Args: - mapping (dict): A dict that needs to be converted to protobuf. - proto_type (str): The type of the Protobuf. - - Returns: - An instance of the specified protobuf. - """ - converted_pb = getattr(trace_pb2, proto_type)() - ParseDict(mapping, converted_pb) - return converted_pb - - -def _span_attrs_to_pb(span_attr, proto_type): - """ - Convert a span attribute dict to protobuf, including Links, Attributes, - TimeEvents. - - Args: - span_attr (dict): A dict that needs to be converted to protobuf. - proto_type (str): The type of the Protobuf. - - Returns: - An instance of the specified protobuf. - """ - attr_pb = getattr(trace_pb2.Span, proto_type)() - ParseDict(span_attr, attr_pb) - return attr_pb - - -def _status_mapping_to_pb(status): - """ - Convert a status dict to protobuf. - - Args: - status (dict): A status that needs to be converted to protobuf. - - Returns: - An instance of the specified protobuf. - """ - status_pb = google_dot_rpc_dot_status__pb2.Status() - ParseDict(status, status_pb) - return status_pb - - -def _value_to_pb(value, proto_type): - """ - Convert a value to protobuf. e.g. BoolValue, Int32Value. - - Args: - value (dict): A dict that needs to be converted to protobuf. - proto_type (str): The type of the Protobuf. - - Returns: - An instance of the specified protobuf. - """ - data_type_pb = getattr(google_dot_protobuf_dot_wrappers__pb2, proto_type)() - ParseDict(value, data_type_pb) - return data_type_pb - - -def make_trace_api(client): - """ - Create an instance of the gapic Trace API. - - Args: - client (:class:`~google.cloud.trace_v2.client.Client`): The client - that holds configuration details. - - Returns: - A :class:`~google.cloud.trace_v2._gapic._TraceAPI` instance with the - proper configurations. - """ - generated = trace_service_client.TraceServiceClient( - credentials=client._credentials, - client_info=client._client_info, - client_options=client._client_options, - ) - return _TraceAPI(generated, client) diff --git a/google/cloud/trace/client.py b/google/cloud/trace/client.py deleted file mode 100644 index 90ddd713..00000000 --- a/google/cloud/trace/client.py +++ /dev/null @@ -1,247 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Client for interacting with the Stackdriver Trace API.""" - -from google.api_core.gapic_v1 import client_info -from google.cloud.client import ClientWithProject -from google.cloud.trace import __version__ -from google.cloud.trace._gapic import make_trace_api - - -_CLIENT_INFO = client_info.ClientInfo(client_library_version=__version__) - - -class Client(ClientWithProject): - """ - Client to bundle configuration needed for API requests. - - Args: - project (str): The project which the client acts on behalf of. - If not passed, falls back to the default inferred from - the environment. - credentials (Optional[:class:`~google.auth.credentials.Credentials`]): - The OAuth2 Credentials to use for this client. If not passed, - falls back to the default inferred from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with API - requests. If ``None``, then default info will be used. Generally, - you only need to set this if you're developing your own library - or partner tool. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - - SCOPE = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/trace.append", - ) - """The scopes required for authenticating as a Trace consumer.""" - - _trace_api = None - - def __init__( - self, - project=None, - credentials=None, - client_info=_CLIENT_INFO, - client_options=None, - ): - super(Client, self).__init__(project=project, credentials=credentials) - self._client_info = client_info - self._client_options = client_options - - @property - def trace_api(self): - """ - Helper for trace-related API calls. - - See - https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools. - cloudtrace.v2 - """ - if self._trace_api is None: - self._trace_api = make_trace_api(self) - return self._trace_api - - def batch_write_spans(self, name, spans, retry=None, timeout=None): - """ - Sends new spans to Stackdriver Trace or updates existing traces. If the - name of a trace that you send matches that of an existing trace, new - spans are added to the existing trace. Attempt to update existing spans - results undefined behavior. If the name does not match, a new trace is - created with given set of spans. - - Example: - >>> from google.cloud import trace_v2 - >>> - >>> client = trace_v2.Client() - >>> - >>> name = 'projects/[PROJECT_ID]' - >>> spans = {'spans': [{'endTime': '2017-11-21T23:50:58.890768Z', - 'spanId': [SPAN_ID], - 'startTime': '2017-11-21T23:50:58.890763Z', - 'name': 'projects/[PROJECT_ID]/traces/ - [TRACE_ID]/spans/[SPAN_ID]', - 'displayName': {'value': 'sample span'}}]} - >>> - >>> client.batch_write_spans(name, spans) - - Args: - name (str): Optional. Name of the project where the spans belong. - The format is ``projects/PROJECT_ID``. - spans (dict): A collection of spans. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will not - be retried. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - self.trace_api.batch_write_spans( - name=name, spans=spans, retry=retry, timeout=timeout - ) - - def create_span( - self, - name, - span_id, - display_name, - start_time, - end_time, - parent_span_id=None, - attributes=None, - stack_trace=None, - time_events=None, - links=None, - status=None, - same_process_as_parent_span=None, - child_span_count=None, - retry=None, - timeout=None, - ): - """ - Creates a new Span. - - Example: - >>> from google.cloud import trace_v2 - >>> - >>> client = trace_v2.Client() - >>> - >>> name = 'projects/{project}/traces/{trace_id}/spans/{span_id}'. - format('[PROJECT]', '[TRACE_ID]', '[SPAN_ID]') - >>> span_id = '[SPAN_ID]' - >>> display_name = {} - >>> start_time = {} - >>> end_time = {} - >>> - >>> response = client.create_span(name, span_id, display_name, - start_time, end_time) - - Args: - name (str): The resource name of the span in the following format: - - :: - - projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] - - [TRACE_ID] is a unique identifier for a trace within a project. - [SPAN_ID] is a unique identifier for a span within a trace, - assigned when the span is created. - span_id (str): The [SPAN_ID] portion of the span's resource name. - The ID is a 16-character hexadecimal encoding of an 8-byte - array. - display_name (dict): A description of the span's operation - (up to 128 bytes). Stackdriver Trace displays the description - in the {% dynamic print site_values.console_name %}. - For example, the display name can be a qualified method name - or a file name and a line number where the operation is called. - A best practice is to use the same display name within an - application and at the same call point. This makes it easier to - correlate spans in different traces. - Contains two fields, value is the truncated name, - truncatedByteCount is the number of bytes removed from the - original string. If 0, then the string was not shortened. - start_time (:class:`~datetime.datetime`): - The start time of the span. On the client side, this is the - time kept by the local machine where the span execution starts. - On the server side, this is the time when the server's - application handler starts running. - end_time (:class:`~datetime.datetime`): - The end time of the span. On the client side, this is the time - kept by the local machine where the span execution ends. On the - server side, this is the time when the server application - handler stops running. - parent_span_id (str): The [SPAN_ID] of this span's parent span. - If this is a root span, then this field must be empty. - attributes (dict): A set of attributes on the span. There is a - limit of 32 attributes per span. - stack_trace (dict): - Stack trace captured at the start of the span. - Contains two fields, stackFrames is a list of stack frames in - this call stack, a maximum of 128 frames are allowed per - StackFrame; stackTraceHashId is used to conserve network - bandwidth for duplicate stack traces within a single trace. - time_events (dict): - The included time events. There can be up to 32 annotations - and 128 message events per span. - links (dict): A maximum of 128 links are allowed per Span. - status (dict): An optional final status for this span. - same_process_as_parent_span (bool): A highly recommended but not - required flag that identifies when a trace crosses a process - boundary. True when the parent_span belongs to the same process - as the current span. - child_span_count (int): An optional number of child spans that were - generated while this span was active. If set, allows - implementation to detect missing child spans. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will not - be retried. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - - Returns: - A :class:`~google.cloud.trace_v2.types.Span` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - return self.trace_api.create_span( - name=name, - span_id=span_id, - display_name=display_name, - start_time=start_time, - end_time=end_time, - parent_span_id=parent_span_id, - attributes=attributes, - stack_trace=stack_trace, - time_events=time_events, - links=links, - status=status, - same_process_as_parent_span=same_process_as_parent_span, - child_span_count=child_span_count, - ) diff --git a/google/cloud/trace/py.typed b/google/cloud/trace/py.typed new file mode 100644 index 00000000..4717a6c0 --- /dev/null +++ b/google/cloud/trace/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-trace package uses inline types. diff --git a/google/cloud/trace/v1/_gapic.py b/google/cloud/trace/v1/_gapic.py deleted file mode 100644 index a5f5b2f7..00000000 --- a/google/cloud/trace/v1/_gapic.py +++ /dev/null @@ -1,200 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrapper for interacting with the Stackdriver Trace API.""" - -from google.api_core.gapic_v1 import client_info -from google.cloud.trace import __version__ -from google.cloud.trace_v1.gapic import trace_service_client -from google.cloud.trace_v1.proto import trace_pb2 -from google.protobuf.json_format import MessageToDict -from google.protobuf.json_format import ParseDict - - -_CLIENT_INFO = client_info.ClientInfo(client_library_version=__version__) - - -class _TraceAPI(object): - """ - Wrapper to help mapping trace-related APIs. - - See - https://cloud.google.com/trace/docs/reference/v1/rpc/google.devtools. - cloudtrace.v1 - - Args: - gapic_api (~google.cloud.trace_v1.gapic.trace_service_client. - TraceServiceClient): Required. API object used to make RPCs. - client (~google.cloud.trace.client.Client): The client that owns this - API object. - """ - - def __init__(self, gapic_api, client): - self._gapic_api = gapic_api - self.client = client - - def patch_traces(self, project_id, traces): - """ - Sends new traces to Stackdriver Trace or updates existing traces. - - Args: - project_id (Optional[str]): ID of the Cloud project where the trace - data is stored. - traces (dict): Required. The traces to be patched in the API call. - """ - traces_pb = _traces_mapping_to_pb(traces) - self._gapic_api.patch_traces(project_id, traces_pb) - - def get_trace(self, project_id, trace_id): - """ - Gets a single trace by its ID. - - Args: - trace_id (str): ID of the trace to return. - project_id (str): Required. ID of the Cloud project where the trace - data is stored. - - Returns: - A Trace dict. - """ - trace_pb = self._gapic_api.get_trace(project_id, trace_id) - trace_mapping = _parse_trace_pb(trace_pb) - return trace_mapping - - def list_traces( - self, - project_id, - view=None, - page_size=None, - start_time=None, - end_time=None, - filter_=None, - order_by=None, - page_token=None, - ): - """ - Returns of a list of traces that match the filter conditions. - - Args: - project_id (Optional[str]): ID of the Cloud project where the trace - data is stored. - - view (Optional[~google.cloud.trace_v1.gapic.enums. - ListTracesRequest.ViewType]): Type of data returned for traces - in the list. Default is ``MINIMAL``. - - page_size (Optional[int]): Maximum number of traces to return. If - not specified or <= 0, the implementation selects a reasonable - value. The implementation may return fewer traces than the - requested page size. - - start_time (Optional[~datetime.datetime]): Start of the time - interval (inclusive) during which the trace data was collected - from the application. - - end_time (Optional[~datetime.datetime]): End of the time interval - (inclusive) during which the trace data was collected from the - application. - - filter_ (Optional[str]): An optional filter for the request. - - order_by (Optional[str]): Field used to sort the returned traces. - - page_token (Optional[str]): opaque marker for the next "page" of - entries. If not passed, the API will return the first page of - entries. - - Returns: - A :class:`~google.api_core.page_iterator.Iterator` of traces that - match the specified filter conditions. - """ - page_iter = self._gapic_api.list_traces( - project_id=project_id, - view=view, - page_size=page_size, - start_time=start_time, - end_time=end_time, - filter_=filter_, - order_by=order_by, - ) - page_iter.item_to_value = _item_to_mapping - page_iter.next_page_token = page_token - return page_iter - - -def _parse_trace_pb(trace_pb): - """ - Parse a ``Trace`` protobuf to a dictionary. - - Args: - trace_pb (~google.cloud.trace_v1.proto.trace_pb2.Trace): A trace - protobuf instance. - - Returns: - The converted trace dict. - """ - try: - return MessageToDict(trace_pb) - except TypeError: - raise - - -def _item_to_mapping(iterator, trace_pb): - """ - Helper callable function for the page iterator - - Args: - iterator(~google.api_core.page_iterator.Iterator): The iterator that is - currently in use. - - trace_pb(~google.cloud.trace_v1.proto.trace_pb2.Trace): A trace - protobuf instance. - """ - mapping = _parse_trace_pb(trace_pb) - return mapping - - -def make_trace_api(client): - """ - Create an instance of the gapic Trace API. - - Args: - client (~google.cloud.trace.client.Client): The client that holds - configuration details. - - Returns: - A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the - proper configurations. - """ - generated = trace_service_client.TraceServiceClient( - credentials=client._credentials, - client_info=client._client_info, - client_options=client._client_options, - ) - return _TraceAPI(generated, client) - - -def _traces_mapping_to_pb(traces_mapping): - """ - Convert a trace dict to protobuf. - - Args: - traces_mapping (dict): A trace mapping. - - Returns: - The converted protobuf type traces. - """ - traces_pb = trace_pb2.Traces() - ParseDict(traces_mapping, traces_pb) - return traces_pb diff --git a/google/cloud/trace/v1/client.py b/google/cloud/trace/v1/client.py deleted file mode 100644 index 2b797730..00000000 --- a/google/cloud/trace/v1/client.py +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Client for interacting with the Stackdriver Trace API.""" - -from google.api_core.gapic_v1 import client_info -from google.cloud._helpers import _datetime_to_pb_timestamp -from google.cloud.client import ClientWithProject -from google.cloud.trace import __version__ -from google.cloud.trace.v1._gapic import make_trace_api - - -_CLIENT_INFO = client_info.ClientInfo(client_library_version=__version__) - - -class Client(ClientWithProject): - """ - Client to bundle configuration needed for API requests. - - Args: - project (str): Required. The project which the client acts on behalf - of. If not passed, falls back to the default inferred - from the environment. - credentials (Optional[~google.auth.credentials.Credentials]): - The OAuth2 Credentials to use for this client. If not - passed, falls back to the default inferred from the - environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with API - requests. If ``None``, then default info will be used. Generally, - you only need to set this if you're developing your own library - or partner tool. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - - SCOPE = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/trace.append", - ) - """The scopes required for authenticating as a Trace consumer.""" - - _trace_api = None - - def __init__( - self, - project=None, - credentials=None, - client_info=_CLIENT_INFO, - client_options=None, - ): - super(Client, self).__init__(project=project, credentials=credentials) - self._client_info = client_info - self._client_options = client_options - - @property - def trace_api(self): - """Helper for trace-related API calls. - - See - https://cloud.google.com/trace/docs/reference/v1/rpc/google.devtools. - cloudtrace.v1 - """ - if self._trace_api is None: - self._trace_api = make_trace_api(self) - return self._trace_api - - def patch_traces(self, traces, project_id=None): - """Sends new traces to Stackdriver Trace or updates existing traces. - - Args: - traces (dict): Required. The traces to be patched in the API call. - - project_id (Optional[str]): ID of the Cloud project where the trace - data is stored. - """ - if project_id is None: - project_id = self.project - - self.trace_api.patch_traces(project_id=project_id, traces=traces) - - def get_trace(self, trace_id, project_id=None): - """ - Gets a single trace by its ID. - - Args: - trace_id (str): ID of the trace to return. - - project_id (str): Required. ID of the Cloud project where the trace - data is stored. - - Returns: - A Trace dict. - """ - if project_id is None: - project_id = self.project - - return self.trace_api.get_trace(project_id=project_id, trace_id=trace_id) - - def list_traces( - self, - project_id=None, - view=None, - page_size=None, - start_time=None, - end_time=None, - filter_=None, - order_by=None, - page_token=None, - ): - """ - Returns of a list of traces that match the filter conditions. - - Args: - project_id (Optional[str]): ID of the Cloud project where the trace - data is stored. - - view (Optional[~google.cloud.trace_v1.gapic.enums. - ListTracesRequest.ViewType]): Type of data returned for traces - in the list. Default is ``MINIMAL``. - - page_size (Optional[int]): Maximum number of traces to return. If - not specified or <= 0, the implementation selects a reasonable - value. The implementation may return fewer traces than the - requested page size. - - start_time (Optional[~datetime.datetime]): Start of the time - interval (inclusive) during which the trace data was collected - from the application. - - end_time (Optional[~datetime.datetime]): End of the time interval - (inclusive) during which the trace data was collected from the - application. - - filter_ (Optional[str]): An optional filter for the request. - - order_by (Optional[str]): Field used to sort the returned traces. - - page_token (Optional[str]): opaque marker for the next "page" of - entries. If not passed, the API will return the first page of - entries. - - Returns: - A :class:`~google.api_core.page_iterator.Iterator` of traces that - match the specified filter conditions. - """ - if project_id is None: - project_id = self.project - - if start_time is not None: - start_time = _datetime_to_pb_timestamp(start_time) - - if end_time is not None: - end_time = _datetime_to_pb_timestamp(end_time) - - return self.trace_api.list_traces( - project_id=project_id, - view=view, - page_size=page_size, - start_time=start_time, - end_time=end_time, - filter_=filter_, - order_by=order_by, - page_token=page_token, - ) diff --git a/google/cloud/trace_v1/__init__.py b/google/cloud/trace_v1/__init__.py index d03ae046..ff19d939 100644 --- a/google/cloud/trace_v1/__init__.py +++ b/google/cloud/trace_v1/__init__.py @@ -1,45 +1,37 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.trace_v1 import types -from google.cloud.trace_v1.gapic import enums -from google.cloud.trace_v1.gapic import trace_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class TraceServiceClient(trace_service_client.TraceServiceClient): - __doc__ = trace_service_client.TraceServiceClient.__doc__ - enums = enums +from .services.trace_service import TraceServiceClient +from .types.trace import GetTraceRequest +from .types.trace import ListTracesRequest +from .types.trace import ListTracesResponse +from .types.trace import PatchTracesRequest +from .types.trace import Trace +from .types.trace import TraceSpan +from .types.trace import Traces __all__ = ( - "enums", - "types", + "GetTraceRequest", + "ListTracesRequest", + "ListTracesResponse", + "PatchTracesRequest", + "Trace", + "TraceSpan", + "Traces", "TraceServiceClient", ) diff --git a/google/cloud/trace_v1/gapic/__init__.py b/google/cloud/trace_v1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/trace_v1/gapic/enums.py b/google/cloud/trace_v1/gapic/enums.py deleted file mode 100644 index 3d5e74ac..00000000 --- a/google/cloud/trace_v1/gapic/enums.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class ListTracesRequest(object): - class ViewType(enum.IntEnum): - """ - Type of data returned for traces in the list. - - Attributes: - VIEW_TYPE_UNSPECIFIED (int): Default is ``MINIMAL`` if unspecified. - MINIMAL (int): Minimal view of the trace record that contains only the project - and trace IDs. - ROOTSPAN (int): Root span view of the trace record that returns the root spans along - with the minimal trace data. - COMPLETE (int): Complete view of the trace record that contains the actual trace - data. This is equivalent to calling the REST ``get`` or RPC ``GetTrace`` - method using the ID of each listed trace. - """ - - VIEW_TYPE_UNSPECIFIED = 0 - MINIMAL = 1 - ROOTSPAN = 2 - COMPLETE = 3 - - -class TraceSpan(object): - class SpanKind(enum.IntEnum): - """ - Type of span. Can be used to specify additional relationships between spans - in addition to a parent/child relationship. - - Attributes: - SPAN_KIND_UNSPECIFIED (int): Unspecified. - RPC_SERVER (int): Indicates that the span covers server-side handling of an RPC or other - remote network request. - RPC_CLIENT (int): Indicates that the span covers the client-side wrapper around an RPC or - other remote request. - """ - - SPAN_KIND_UNSPECIFIED = 0 - RPC_SERVER = 1 - RPC_CLIENT = 2 diff --git a/google/cloud/trace_v1/gapic/trace_service_client.py b/google/cloud/trace_v1/gapic/trace_service_client.py deleted file mode 100644 index 5826bcef..00000000 --- a/google/cloud/trace_v1/gapic/trace_service_client.py +++ /dev/null @@ -1,503 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.devtools.cloudtrace.v1 TraceService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import grpc - -from google.cloud.trace_v1.gapic import enums -from google.cloud.trace_v1.gapic import trace_service_client_config -from google.cloud.trace_v1.gapic.transports import trace_service_grpc_transport -from google.cloud.trace_v1.proto import trace_pb2 -from google.cloud.trace_v1.proto import trace_pb2_grpc -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-trace",).version - - -class TraceServiceClient(object): - """ - This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. Spans for a single trace - may span multiple services. - """ - - SERVICE_ADDRESS = "cloudtrace.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.devtools.cloudtrace.v1.TraceService" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - TraceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.TraceServiceGrpcTransport, - Callable[[~.Credentials, type], ~.TraceServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = trace_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=trace_service_grpc_transport.TraceServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = trace_service_grpc_transport.TraceServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def patch_traces( - self, - project_id, - traces, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sends new traces to Stackdriver Trace or updates existing traces. If the ID - of a trace that you send matches that of an existing trace, any fields - in the existing trace and its spans are overwritten by the provided values, - and any new fields provided are merged with the existing trace data. If the - ID does not match, a new trace is created. - - Example: - >>> from google.cloud import trace_v1 - >>> - >>> client = trace_v1.TraceServiceClient() - >>> - >>> # TODO: Initialize `project_id`: - >>> project_id = '' - >>> - >>> # TODO: Initialize `traces`: - >>> traces = {} - >>> - >>> client.patch_traces(project_id, traces) - - Args: - project_id (str): Required. ID of the Cloud project where the trace data is stored. - traces (Union[dict, ~google.cloud.trace_v1.types.Traces]): Required. The body of the message. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v1.types.Traces` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "patch_traces" not in self._inner_api_calls: - self._inner_api_calls[ - "patch_traces" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.patch_traces, - default_retry=self._method_configs["PatchTraces"].retry, - default_timeout=self._method_configs["PatchTraces"].timeout, - client_info=self._client_info, - ) - - request = trace_pb2.PatchTracesRequest(project_id=project_id, traces=traces,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("project_id", project_id)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["patch_traces"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_traces( - self, - project_id, - view=None, - page_size=None, - start_time=None, - end_time=None, - filter_=None, - order_by=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns of a list of traces that match the specified filter conditions. - - Example: - >>> from google.cloud import trace_v1 - >>> - >>> client = trace_v1.TraceServiceClient() - >>> - >>> # TODO: Initialize `project_id`: - >>> project_id = '' - >>> - >>> # Iterate over all results - >>> for element in client.list_traces(project_id): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_traces(project_id).pages: - ... for element in page: - ... # process element - ... pass - - Args: - project_id (str): Required. ID of the Cloud project where the trace data is stored. - view (~google.cloud.trace_v1.types.ViewType): Optional. Type of data returned for traces in the list. Default is - ``MINIMAL``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - start_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): Start of the time interval (inclusive) during which the trace data was - collected from the application. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v1.types.Timestamp` - end_time (Union[dict, ~google.cloud.trace_v1.types.Timestamp]): End of the time interval (inclusive) during which the trace data was - collected from the application. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v1.types.Timestamp` - filter_ (str): Optional. A filter against labels for the request. - - By default, searches use prefix matching. To specify exact match, - prepend a plus symbol (``+``) to the search term. Multiple terms are - ANDed. Syntax: - - - ``root:NAME_PREFIX`` or ``NAME_PREFIX``: Return traces where any root - span starts with ``NAME_PREFIX``. - - ``+root:NAME`` or ``+NAME``: Return traces where any root span's name - is exactly ``NAME``. - - ``span:NAME_PREFIX``: Return traces where any span starts with - ``NAME_PREFIX``. - - ``+span:NAME``: Return traces where any span's name is exactly - ``NAME``. - - ``latency:DURATION``: Return traces whose overall latency is greater - or equal to than ``DURATION``. Accepted units are nanoseconds - (``ns``), milliseconds (``ms``), and seconds (``s``). Default is - ``ms``. For example, ``latency:24ms`` returns traces whose overall - latency is greater than or equal to 24 milliseconds. - - ``label:LABEL_KEY``: Return all traces containing the specified label - key (exact match, case-sensitive) regardless of the key:value pair's - value (including empty values). - - ``LABEL_KEY:VALUE_PREFIX``: Return all traces containing the - specified label key (exact match, case-sensitive) whose value starts - with ``VALUE_PREFIX``. Both a key and a value must be specified. - - ``+LABEL_KEY:VALUE``: Return all traces containing a key:value pair - exactly matching the specified text. Both a key and a value must be - specified. - - ``method:VALUE``: Equivalent to ``/http/method:VALUE``. - - ``url:VALUE``: Equivalent to ``/http/url:VALUE``. - order_by (str): Optional. Field used to sort the returned traces. Can be one of the - following: - - - ``trace_id`` - - ``name`` (``name`` field of root span in the trace) - - ``duration`` (difference between ``end_time`` and ``start_time`` - fields of the root span) - - ``start`` (``start_time`` field of the root span) - - Descending order can be specified by appending ``desc`` to the sort - field (for example, ``name desc``). - - Only one sort field is permitted. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.trace_v1.types.Trace` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_traces" not in self._inner_api_calls: - self._inner_api_calls[ - "list_traces" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_traces, - default_retry=self._method_configs["ListTraces"].retry, - default_timeout=self._method_configs["ListTraces"].timeout, - client_info=self._client_info, - ) - - request = trace_pb2.ListTracesRequest( - project_id=project_id, - view=view, - page_size=page_size, - start_time=start_time, - end_time=end_time, - filter=filter_, - order_by=order_by, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("project_id", project_id)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_traces"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="traces", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_trace( - self, - project_id, - trace_id, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a single trace by its ID. - - Example: - >>> from google.cloud import trace_v1 - >>> - >>> client = trace_v1.TraceServiceClient() - >>> - >>> # TODO: Initialize `project_id`: - >>> project_id = '' - >>> - >>> # TODO: Initialize `trace_id`: - >>> trace_id = '' - >>> - >>> response = client.get_trace(project_id, trace_id) - - Args: - project_id (str): Required. ID of the Cloud project where the trace data is stored. - trace_id (str): Required. ID of the trace to return. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.trace_v1.types.Trace` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_trace" not in self._inner_api_calls: - self._inner_api_calls[ - "get_trace" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_trace, - default_retry=self._method_configs["GetTrace"].retry, - default_timeout=self._method_configs["GetTrace"].timeout, - client_info=self._client_info, - ) - - request = trace_pb2.GetTraceRequest(project_id=project_id, trace_id=trace_id,) - return self._inner_api_calls["get_trace"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/trace_v1/gapic/trace_service_client_config.py b/google/cloud/trace_v1/gapic/trace_service_client_config.py deleted file mode 100644 index 7f164f17..00000000 --- a/google/cloud/trace_v1/gapic/trace_service_client_config.py +++ /dev/null @@ -1,47 +0,0 @@ -config = { - "interfaces": { - "google.devtools.cloudtrace.v1.TraceService": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], - "no_retry_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.2, - "max_retry_delay_millis": 1000, - "initial_rpc_timeout_millis": 45000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 45000, - "total_timeout_millis": 45000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "PatchTraces": { - "timeout_millis": 45000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "ListTraces": { - "timeout_millis": 45000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetTrace": { - "timeout_millis": 45000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/trace_v1/gapic/transports/__init__.py b/google/cloud/trace_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/trace_v1/gapic/transports/trace_service_grpc_transport.py b/google/cloud/trace_v1/gapic/transports/trace_service_grpc_transport.py deleted file mode 100644 index 0b8be078..00000000 --- a/google/cloud/trace_v1/gapic/transports/trace_service_grpc_transport.py +++ /dev/null @@ -1,155 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.trace_v1.proto import trace_pb2_grpc - - -class TraceServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.devtools.cloudtrace.v1 TraceService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/trace.append", - "https://www.googleapis.com/auth/trace.readonly", - ) - - def __init__( - self, channel=None, credentials=None, address="cloudtrace.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "trace_service_stub": trace_pb2_grpc.TraceServiceStub(channel), - } - - @classmethod - def create_channel( - cls, address="cloudtrace.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def patch_traces(self): - """Return the gRPC stub for :meth:`TraceServiceClient.patch_traces`. - - Sends new traces to Stackdriver Trace or updates existing traces. If the ID - of a trace that you send matches that of an existing trace, any fields - in the existing trace and its spans are overwritten by the provided values, - and any new fields provided are merged with the existing trace data. If the - ID does not match, a new trace is created. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["trace_service_stub"].PatchTraces - - @property - def list_traces(self): - """Return the gRPC stub for :meth:`TraceServiceClient.list_traces`. - - Returns of a list of traces that match the specified filter conditions. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["trace_service_stub"].ListTraces - - @property - def get_trace(self): - """Return the gRPC stub for :meth:`TraceServiceClient.get_trace`. - - Gets a single trace by its ID. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["trace_service_stub"].GetTrace diff --git a/google/cloud/trace_v1/proto/__init__.py b/google/cloud/trace_v1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/trace_v1/proto/trace.proto b/google/cloud/trace_v1/proto/trace.proto deleted file mode 100644 index d3948fa1..00000000 --- a/google/cloud/trace_v1/proto/trace.proto +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright 2020 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.devtools.cloudtrace.v1; - -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/timestamp.proto"; -import "google/api/annotations.proto"; - -option csharp_namespace = "Google.Cloud.Trace.V1"; -option go_package = "google.golang.org/genproto/googleapis/devtools/cloudtrace/v1;cloudtrace"; -option java_multiple_files = true; -option java_outer_classname = "TraceProto"; -option java_package = "com.google.devtools.cloudtrace.v1"; -option php_namespace = "Google\\Cloud\\Trace\\V1"; -option ruby_package = "Google::Cloud::Trace::V1"; - -// This file describes an API for collecting and viewing traces and spans -// within a trace. A Trace is a collection of spans corresponding to a single -// operation or set of operations for an application. A span is an individual -// timed event which forms a node of the trace tree. Spans for a single trace -// may span multiple services. -service TraceService { - option (google.api.default_host) = "cloudtrace.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/trace.append," - "https://www.googleapis.com/auth/trace.readonly"; - - // Returns of a list of traces that match the specified filter conditions. - rpc ListTraces(ListTracesRequest) returns (ListTracesResponse) { - option (google.api.http) = { - get: "/v1/projects/{project_id}/traces" - }; - option (google.api.method_signature) = "project_id"; - } - - // Gets a single trace by its ID. - rpc GetTrace(GetTraceRequest) returns (Trace) { - option (google.api.http) = { - get: "/v1/projects/{project_id}/traces/{trace_id}" - }; - option (google.api.method_signature) = "project_id,trace_id"; - } - - // Sends new traces to Stackdriver Trace or updates existing traces. If the ID - // of a trace that you send matches that of an existing trace, any fields - // in the existing trace and its spans are overwritten by the provided values, - // and any new fields provided are merged with the existing trace data. If the - // ID does not match, a new trace is created. - rpc PatchTraces(PatchTracesRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - patch: "/v1/projects/{project_id}/traces" - body: "traces" - }; - option (google.api.method_signature) = "project_id,traces"; - } -} - -// A trace describes how long it takes for an application to perform an -// operation. It consists of a set of spans, each of which represent a single -// timed event within the operation. -message Trace { - // Project ID of the Cloud project where the trace data is stored. - string project_id = 1; - - // Globally unique identifier for the trace. This identifier is a 128-bit - // numeric value formatted as a 32-byte hex string. For example, - // `382d4f4c6b7bb2f4a972559d9085001d`. - string trace_id = 2; - - // Collection of spans in the trace. - repeated TraceSpan spans = 3; -} - -// List of new or updated traces. -message Traces { - // List of traces. - repeated Trace traces = 1; -} - -// A span represents a single timed event within a trace. Spans can be nested -// and form a trace tree. Often, a trace contains a root span that describes the -// end-to-end latency of an operation and, optionally, one or more subspans for -// its suboperations. Spans do not need to be contiguous. There may be gaps -// between spans in a trace. -message TraceSpan { - // Type of span. Can be used to specify additional relationships between spans - // in addition to a parent/child relationship. - enum SpanKind { - // Unspecified. - SPAN_KIND_UNSPECIFIED = 0; - - // Indicates that the span covers server-side handling of an RPC or other - // remote network request. - RPC_SERVER = 1; - - // Indicates that the span covers the client-side wrapper around an RPC or - // other remote request. - RPC_CLIENT = 2; - } - - // Identifier for the span. Must be a 64-bit integer other than 0 and - // unique within a trace. For example, `2205310701640571284`. - fixed64 span_id = 1; - - // Distinguishes between spans generated in a particular context. For example, - // two spans with the same name may be distinguished using `RPC_CLIENT` - // and `RPC_SERVER` to identify queueing latency associated with the span. - SpanKind kind = 2; - - // Name of the span. Must be less than 128 bytes. The span name is sanitized - // and displayed in the Stackdriver Trace tool in the - // Google Cloud Platform Console. - // The name may be a method name or some other per-call site name. - // For the same executable and the same call point, a best practice is - // to use a consistent name, which makes it easier to correlate - // cross-trace spans. - string name = 3; - - // Start time of the span in nanoseconds from the UNIX epoch. - google.protobuf.Timestamp start_time = 4; - - // End time of the span in nanoseconds from the UNIX epoch. - google.protobuf.Timestamp end_time = 5; - - // Optional. ID of the parent span, if any. - fixed64 parent_span_id = 6 [(google.api.field_behavior) = OPTIONAL]; - - // Collection of labels associated with the span. Label keys must be less than - // 128 bytes. Label values must be less than 16 kilobytes (10MB for - // `/stacktrace` values). - // - // Some predefined label keys exist, or you may create your own. When creating - // your own, we recommend the following formats: - // - // * `/category/product/key` for agents of well-known products (e.g. - // `/db/mongodb/read_size`). - // * `short_host/path/key` for domain-specific keys (e.g. - // `foo.com/myproduct/bar`) - // - // Predefined labels include: - // - // * `/agent` - // * `/component` - // * `/error/message` - // * `/error/name` - // * `/http/client_city` - // * `/http/client_country` - // * `/http/client_protocol` - // * `/http/client_region` - // * `/http/host` - // * `/http/method` - // * `/http/path` - // * `/http/redirected_url` - // * `/http/request/size` - // * `/http/response/size` - // * `/http/route` - // * `/http/status_code` - // * `/http/url` - // * `/http/user_agent` - // * `/pid` - // * `/stacktrace` - // * `/tid` - map labels = 7; -} - -// The request message for the `ListTraces` method. All fields are required -// unless specified. -message ListTracesRequest { - // Type of data returned for traces in the list. - enum ViewType { - // Default is `MINIMAL` if unspecified. - VIEW_TYPE_UNSPECIFIED = 0; - - // Minimal view of the trace record that contains only the project - // and trace IDs. - MINIMAL = 1; - - // Root span view of the trace record that returns the root spans along - // with the minimal trace data. - ROOTSPAN = 2; - - // Complete view of the trace record that contains the actual trace data. - // This is equivalent to calling the REST `get` or RPC `GetTrace` method - // using the ID of each listed trace. - COMPLETE = 3; - } - - // Required. ID of the Cloud project where the trace data is stored. - string project_id = 1 [(google.api.field_behavior) = REQUIRED]; - - // Optional. Type of data returned for traces in the list. Default is - // `MINIMAL`. - ViewType view = 2 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Maximum number of traces to return. If not specified or <= 0, the - // implementation selects a reasonable value. The implementation may - // return fewer traces than the requested page size. - int32 page_size = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Token identifying the page of results to return. If provided, use the - // value of the `next_page_token` field from a previous request. - string page_token = 4; - - // Start of the time interval (inclusive) during which the trace data was - // collected from the application. - google.protobuf.Timestamp start_time = 5; - - // End of the time interval (inclusive) during which the trace data was - // collected from the application. - google.protobuf.Timestamp end_time = 6; - - // Optional. A filter against labels for the request. - // - // By default, searches use prefix matching. To specify exact match, prepend - // a plus symbol (`+`) to the search term. - // Multiple terms are ANDed. Syntax: - // - // * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root - // span starts with `NAME_PREFIX`. - // * `+root:NAME` or `+NAME`: Return traces where any root span's name is - // exactly `NAME`. - // * `span:NAME_PREFIX`: Return traces where any span starts with - // `NAME_PREFIX`. - // * `+span:NAME`: Return traces where any span's name is exactly - // `NAME`. - // * `latency:DURATION`: Return traces whose overall latency is - // greater or equal to than `DURATION`. Accepted units are nanoseconds - // (`ns`), milliseconds (`ms`), and seconds (`s`). Default is `ms`. For - // example, `latency:24ms` returns traces whose overall latency - // is greater than or equal to 24 milliseconds. - // * `label:LABEL_KEY`: Return all traces containing the specified - // label key (exact match, case-sensitive) regardless of the key:value - // pair's value (including empty values). - // * `LABEL_KEY:VALUE_PREFIX`: Return all traces containing the specified - // label key (exact match, case-sensitive) whose value starts with - // `VALUE_PREFIX`. Both a key and a value must be specified. - // * `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair - // exactly matching the specified text. Both a key and a value must be - // specified. - // * `method:VALUE`: Equivalent to `/http/method:VALUE`. - // * `url:VALUE`: Equivalent to `/http/url:VALUE`. - string filter = 7 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Field used to sort the returned traces. - // Can be one of the following: - // - // * `trace_id` - // * `name` (`name` field of root span in the trace) - // * `duration` (difference between `end_time` and `start_time` fields of - // the root span) - // * `start` (`start_time` field of the root span) - // - // Descending order can be specified by appending `desc` to the sort field - // (for example, `name desc`). - // - // Only one sort field is permitted. - string order_by = 8 [(google.api.field_behavior) = OPTIONAL]; -} - -// The response message for the `ListTraces` method. -message ListTracesResponse { - // List of trace records as specified by the view parameter. - repeated Trace traces = 1; - - // If defined, indicates that there are more traces that match the request - // and that this value should be passed to the next request to continue - // retrieving additional traces. - string next_page_token = 2; -} - -// The request message for the `GetTrace` method. -message GetTraceRequest { - // Required. ID of the Cloud project where the trace data is stored. - string project_id = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. ID of the trace to return. - string trace_id = 2 [(google.api.field_behavior) = REQUIRED]; -} - -// The request message for the `PatchTraces` method. -message PatchTracesRequest { - // Required. ID of the Cloud project where the trace data is stored. - string project_id = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. The body of the message. - Traces traces = 2 [(google.api.field_behavior) = REQUIRED]; -} diff --git a/google/cloud/trace_v1/proto/trace_pb2.py b/google/cloud/trace_v1/proto/trace_pb2.py deleted file mode 100644 index ed7b02e3..00000000 --- a/google/cloud/trace_v1/proto/trace_pb2.py +++ /dev/null @@ -1,1155 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/devtools/cloudtrace_v1/proto/trace.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/devtools/cloudtrace_v1/proto/trace.proto", - package="google.devtools.cloudtrace.v1", - syntax="proto3", - serialized_options=b"\n!com.google.devtools.cloudtrace.v1B\nTraceProtoP\001ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v1;cloudtrace\252\002\025Google.Cloud.Trace.V1\312\002\025Google\\Cloud\\Trace\\V1\352\002\030Google::Cloud::Trace::V1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n5google/cloud/devtools/cloudtrace_v1/proto/trace.proto\x12\x1dgoogle.devtools.cloudtrace.v1\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto"f\n\x05Trace\x12\x12\n\nproject_id\x18\x01 \x01(\t\x12\x10\n\x08trace_id\x18\x02 \x01(\t\x12\x37\n\x05spans\x18\x03 \x03(\x0b\x32(.google.devtools.cloudtrace.v1.TraceSpan">\n\x06Traces\x12\x34\n\x06traces\x18\x01 \x03(\x0b\x32$.google.devtools.cloudtrace.v1.Trace"\xa2\x03\n\tTraceSpan\x12\x0f\n\x07span_id\x18\x01 \x01(\x06\x12?\n\x04kind\x18\x02 \x01(\x0e\x32\x31.google.devtools.cloudtrace.v1.TraceSpan.SpanKind\x12\x0c\n\x04name\x18\x03 \x01(\t\x12.\n\nstart_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1b\n\x0eparent_span_id\x18\x06 \x01(\x06\x42\x03\xe0\x41\x01\x12\x44\n\x06labels\x18\x07 \x03(\x0b\x32\x34.google.devtools.cloudtrace.v1.TraceSpan.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"E\n\x08SpanKind\x12\x19\n\x15SPAN_KIND_UNSPECIFIED\x10\x00\x12\x0e\n\nRPC_SERVER\x10\x01\x12\x0e\n\nRPC_CLIENT\x10\x02"\x80\x03\n\x11ListTracesRequest\x12\x17\n\nproject_id\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12L\n\x04view\x18\x02 \x01(\x0e\x32\x39.google.devtools.cloudtrace.v1.ListTracesRequest.ViewTypeB\x03\xe0\x41\x01\x12\x16\n\tpage_size\x18\x03 \x01(\x05\x42\x03\xe0\x41\x01\x12\x12\n\npage_token\x18\x04 \x01(\t\x12.\n\nstart_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x13\n\x06\x66ilter\x18\x07 \x01(\tB\x03\xe0\x41\x01\x12\x15\n\x08order_by\x18\x08 \x01(\tB\x03\xe0\x41\x01"N\n\x08ViewType\x12\x19\n\x15VIEW_TYPE_UNSPECIFIED\x10\x00\x12\x0b\n\x07MINIMAL\x10\x01\x12\x0c\n\x08ROOTSPAN\x10\x02\x12\x0c\n\x08\x43OMPLETE\x10\x03"c\n\x12ListTracesResponse\x12\x34\n\x06traces\x18\x01 \x03(\x0b\x32$.google.devtools.cloudtrace.v1.Trace\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"A\n\x0fGetTraceRequest\x12\x17\n\nproject_id\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x15\n\x08trace_id\x18\x02 \x01(\tB\x03\xe0\x41\x02"i\n\x12PatchTracesRequest\x12\x17\n\nproject_id\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12:\n\x06traces\x18\x02 \x01(\x0b\x32%.google.devtools.cloudtrace.v1.TracesB\x03\xe0\x41\x02\x32\xb5\x05\n\x0cTraceService\x12\xa8\x01\n\nListTraces\x12\x30.google.devtools.cloudtrace.v1.ListTracesRequest\x1a\x31.google.devtools.cloudtrace.v1.ListTracesResponse"5\x82\xd3\xe4\x93\x02"\x12 /v1/projects/{project_id}/traces\xda\x41\nproject_id\x12\xab\x01\n\x08GetTrace\x12..google.devtools.cloudtrace.v1.GetTraceRequest\x1a$.google.devtools.cloudtrace.v1.Trace"I\x82\xd3\xe4\x93\x02-\x12+/v1/projects/{project_id}/traces/{trace_id}\xda\x41\x13project_id,trace_id\x12\x9e\x01\n\x0bPatchTraces\x12\x31.google.devtools.cloudtrace.v1.PatchTracesRequest\x1a\x16.google.protobuf.Empty"D\x82\xd3\xe4\x93\x02*2 /v1/projects/{project_id}/traces:\x06traces\xda\x41\x11project_id,traces\x1a\xaa\x01\xca\x41\x19\x63loudtrace.googleapis.com\xd2\x41\x8a\x01https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/trace.append,https://www.googleapis.com/auth/trace.readonlyB\xc5\x01\n!com.google.devtools.cloudtrace.v1B\nTraceProtoP\x01ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v1;cloudtrace\xaa\x02\x15Google.Cloud.Trace.V1\xca\x02\x15Google\\Cloud\\Trace\\V1\xea\x02\x18Google::Cloud::Trace::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_TRACESPAN_SPANKIND = _descriptor.EnumDescriptor( - name="SpanKind", - full_name="google.devtools.cloudtrace.v1.TraceSpan.SpanKind", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="SPAN_KIND_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RPC_SERVER", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RPC_CLIENT", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=783, - serialized_end=852, -) -_sym_db.RegisterEnumDescriptor(_TRACESPAN_SPANKIND) - -_LISTTRACESREQUEST_VIEWTYPE = _descriptor.EnumDescriptor( - name="ViewType", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.ViewType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="VIEW_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MINIMAL", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ROOTSPAN", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COMPLETE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1161, - serialized_end=1239, -) -_sym_db.RegisterEnumDescriptor(_LISTTRACESREQUEST_VIEWTYPE) - - -_TRACE = _descriptor.Descriptor( - name="Trace", - full_name="google.devtools.cloudtrace.v1.Trace", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="project_id", - full_name="google.devtools.cloudtrace.v1.Trace.project_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="trace_id", - full_name="google.devtools.cloudtrace.v1.Trace.trace_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="spans", - full_name="google.devtools.cloudtrace.v1.Trace.spans", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=265, - serialized_end=367, -) - - -_TRACES = _descriptor.Descriptor( - name="Traces", - full_name="google.devtools.cloudtrace.v1.Traces", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="traces", - full_name="google.devtools.cloudtrace.v1.Traces.traces", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=369, - serialized_end=431, -) - - -_TRACESPAN_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.devtools.cloudtrace.v1.TraceSpan.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.devtools.cloudtrace.v1.TraceSpan.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.devtools.cloudtrace.v1.TraceSpan.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=736, - serialized_end=781, -) - -_TRACESPAN = _descriptor.Descriptor( - name="TraceSpan", - full_name="google.devtools.cloudtrace.v1.TraceSpan", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="span_id", - full_name="google.devtools.cloudtrace.v1.TraceSpan.span_id", - index=0, - number=1, - type=6, - cpp_type=4, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="kind", - full_name="google.devtools.cloudtrace.v1.TraceSpan.kind", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.devtools.cloudtrace.v1.TraceSpan.name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.devtools.cloudtrace.v1.TraceSpan.start_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.devtools.cloudtrace.v1.TraceSpan.end_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_span_id", - full_name="google.devtools.cloudtrace.v1.TraceSpan.parent_span_id", - index=5, - number=6, - type=6, - cpp_type=4, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.devtools.cloudtrace.v1.TraceSpan.labels", - index=6, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_TRACESPAN_LABELSENTRY,], - enum_types=[_TRACESPAN_SPANKIND,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=434, - serialized_end=852, -) - - -_LISTTRACESREQUEST = _descriptor.Descriptor( - name="ListTracesRequest", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="project_id", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.project_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="view", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.view", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.page_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.page_token", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.start_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.end_time", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.filter", - index=6, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="order_by", - full_name="google.devtools.cloudtrace.v1.ListTracesRequest.order_by", - index=7, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_LISTTRACESREQUEST_VIEWTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=855, - serialized_end=1239, -) - - -_LISTTRACESRESPONSE = _descriptor.Descriptor( - name="ListTracesResponse", - full_name="google.devtools.cloudtrace.v1.ListTracesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="traces", - full_name="google.devtools.cloudtrace.v1.ListTracesResponse.traces", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.devtools.cloudtrace.v1.ListTracesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1241, - serialized_end=1340, -) - - -_GETTRACEREQUEST = _descriptor.Descriptor( - name="GetTraceRequest", - full_name="google.devtools.cloudtrace.v1.GetTraceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="project_id", - full_name="google.devtools.cloudtrace.v1.GetTraceRequest.project_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="trace_id", - full_name="google.devtools.cloudtrace.v1.GetTraceRequest.trace_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1342, - serialized_end=1407, -) - - -_PATCHTRACESREQUEST = _descriptor.Descriptor( - name="PatchTracesRequest", - full_name="google.devtools.cloudtrace.v1.PatchTracesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="project_id", - full_name="google.devtools.cloudtrace.v1.PatchTracesRequest.project_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="traces", - full_name="google.devtools.cloudtrace.v1.PatchTracesRequest.traces", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1409, - serialized_end=1514, -) - -_TRACE.fields_by_name["spans"].message_type = _TRACESPAN -_TRACES.fields_by_name["traces"].message_type = _TRACE -_TRACESPAN_LABELSENTRY.containing_type = _TRACESPAN -_TRACESPAN.fields_by_name["kind"].enum_type = _TRACESPAN_SPANKIND -_TRACESPAN.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_TRACESPAN.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_TRACESPAN.fields_by_name["labels"].message_type = _TRACESPAN_LABELSENTRY -_TRACESPAN_SPANKIND.containing_type = _TRACESPAN -_LISTTRACESREQUEST.fields_by_name["view"].enum_type = _LISTTRACESREQUEST_VIEWTYPE -_LISTTRACESREQUEST.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTTRACESREQUEST.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTTRACESREQUEST_VIEWTYPE.containing_type = _LISTTRACESREQUEST -_LISTTRACESRESPONSE.fields_by_name["traces"].message_type = _TRACE -_PATCHTRACESREQUEST.fields_by_name["traces"].message_type = _TRACES -DESCRIPTOR.message_types_by_name["Trace"] = _TRACE -DESCRIPTOR.message_types_by_name["Traces"] = _TRACES -DESCRIPTOR.message_types_by_name["TraceSpan"] = _TRACESPAN -DESCRIPTOR.message_types_by_name["ListTracesRequest"] = _LISTTRACESREQUEST -DESCRIPTOR.message_types_by_name["ListTracesResponse"] = _LISTTRACESRESPONSE -DESCRIPTOR.message_types_by_name["GetTraceRequest"] = _GETTRACEREQUEST -DESCRIPTOR.message_types_by_name["PatchTracesRequest"] = _PATCHTRACESREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Trace = _reflection.GeneratedProtocolMessageType( - "Trace", - (_message.Message,), - { - "DESCRIPTOR": _TRACE, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2", - "__doc__": """A trace describes how long it takes for an application to perform an - operation. It consists of a set of spans, each of which represent a - single timed event within the operation. - - Attributes: - project_id: - Project ID of the Cloud project where the trace data is - stored. - trace_id: - Globally unique identifier for the trace. This identifier is a - 128-bit numeric value formatted as a 32-byte hex string. For - example, ``382d4f4c6b7bb2f4a972559d9085001d``. - spans: - Collection of spans in the trace. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.Trace) - }, -) -_sym_db.RegisterMessage(Trace) - -Traces = _reflection.GeneratedProtocolMessageType( - "Traces", - (_message.Message,), - { - "DESCRIPTOR": _TRACES, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2", - "__doc__": """List of new or updated traces. - - Attributes: - traces: - List of traces. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.Traces) - }, -) -_sym_db.RegisterMessage(Traces) - -TraceSpan = _reflection.GeneratedProtocolMessageType( - "TraceSpan", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _TRACESPAN_LABELSENTRY, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2" - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.TraceSpan.LabelsEntry) - }, - ), - "DESCRIPTOR": _TRACESPAN, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2", - "__doc__": """A span represents a single timed event within a trace. Spans can be - nested and form a trace tree. Often, a trace contains a root span that - describes the end-to-end latency of an operation and, optionally, one - or more subspans for its suboperations. Spans do not need to be - contiguous. There may be gaps between spans in a trace. - - Attributes: - span_id: - Identifier for the span. Must be a 64-bit integer other than 0 - and unique within a trace. For example, - ``2205310701640571284``. - kind: - Distinguishes between spans generated in a particular context. - For example, two spans with the same name may be distinguished - using ``RPC_CLIENT`` and ``RPC_SERVER`` to identify queueing - latency associated with the span. - name: - Name of the span. Must be less than 128 bytes. The span name - is sanitized and displayed in the Stackdriver Trace tool in - the Google Cloud Platform Console. The name may be a method - name or some other per-call site name. For the same executable - and the same call point, a best practice is to use a - consistent name, which makes it easier to correlate cross- - trace spans. - start_time: - Start time of the span in nanoseconds from the UNIX epoch. - end_time: - End time of the span in nanoseconds from the UNIX epoch. - parent_span_id: - Optional. ID of the parent span, if any. - labels: - Collection of labels associated with the span. Label keys must - be less than 128 bytes. Label values must be less than 16 - kilobytes (10MB for ``/stacktrace`` values). Some predefined - label keys exist, or you may create your own. When creating - your own, we recommend the following formats: - - ``/category/product/key`` for agents of well-known products - (e.g. ``/db/mongodb/read_size``). - - ``short_host/path/key`` for domain-specific keys (e.g. - ``foo.com/myproduct/bar``) Predefined labels include: - - ``/agent`` - ``/component`` - ``/error/message`` - - ``/error/name`` - ``/http/client_city`` - - ``/http/client_country`` - ``/http/client_protocol`` - - ``/http/client_region`` - ``/http/host`` - ``/http/method`` - - ``/http/path`` - ``/http/redirected_url`` - - ``/http/request/size`` - ``/http/response/size`` - - ``/http/route`` - ``/http/status_code`` - ``/http/url`` - - ``/http/user_agent`` - ``/pid`` - ``/stacktrace`` - - ``/tid`` - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.TraceSpan) - }, -) -_sym_db.RegisterMessage(TraceSpan) -_sym_db.RegisterMessage(TraceSpan.LabelsEntry) - -ListTracesRequest = _reflection.GeneratedProtocolMessageType( - "ListTracesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTTRACESREQUEST, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2", - "__doc__": """The request message for the ``ListTraces`` method. All fields are - required unless specified. - - Attributes: - project_id: - Required. ID of the Cloud project where the trace data is - stored. - view: - Optional. Type of data returned for traces in the list. - Default is ``MINIMAL``. - page_size: - Optional. Maximum number of traces to return. If not specified - or <= 0, the implementation selects a reasonable value. The - implementation may return fewer traces than the requested page - size. - page_token: - Token identifying the page of results to return. If provided, - use the value of the ``next_page_token`` field from a previous - request. - start_time: - Start of the time interval (inclusive) during which the trace - data was collected from the application. - end_time: - End of the time interval (inclusive) during which the trace - data was collected from the application. - filter: - Optional. A filter against labels for the request. By - default, searches use prefix matching. To specify exact match, - prepend a plus symbol (``+``) to the search term. Multiple - terms are ANDed. Syntax: - ``root:NAME_PREFIX`` or - ``NAME_PREFIX``: Return traces where any root span starts - with ``NAME_PREFIX``. - ``+root:NAME`` or ``+NAME``: Return - traces where any root span’s name is exactly ``NAME``. - - ``span:NAME_PREFIX``: Return traces where any span starts with - ``NAME_PREFIX``. - ``+span:NAME``: Return traces where any - span’s name is exactly ``NAME``. - ``latency:DURATION``: - Return traces whose overall latency is greater or equal to - than ``DURATION``. Accepted units are nanoseconds (``ns``), - milliseconds (``ms``), and seconds (``s``). Default is - ``ms``. For example, ``latency:24ms`` returns traces whose - overall latency is greater than or equal to 24 - milliseconds. - ``label:LABEL_KEY``: Return all traces - containing the specified label key (exact match, case- - sensitive) regardless of the key:value pair’s value - (including empty values). - ``LABEL_KEY:VALUE_PREFIX``: - Return all traces containing the specified label key (exact - match, case-sensitive) whose value starts with - ``VALUE_PREFIX``. Both a key and a value must be specified. - - ``+LABEL_KEY:VALUE``: Return all traces containing a key:value - pair exactly matching the specified text. Both a key and a - value must be specified. - ``method:VALUE``: Equivalent to - ``/http/method:VALUE``. - ``url:VALUE``: Equivalent to - ``/http/url:VALUE``. - order_by: - Optional. Field used to sort the returned traces. Can be one - of the following: - ``trace_id`` - ``name`` (``name`` field - of root span in the trace) - ``duration`` (difference between - ``end_time`` and ``start_time`` fields of the root span) - - ``start`` (``start_time`` field of the root span) Descending - order can be specified by appending ``desc`` to the sort field - (for example, ``name desc``). Only one sort field is - permitted. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.ListTracesRequest) - }, -) -_sym_db.RegisterMessage(ListTracesRequest) - -ListTracesResponse = _reflection.GeneratedProtocolMessageType( - "ListTracesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTTRACESRESPONSE, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2", - "__doc__": """The response message for the ``ListTraces`` method. - - Attributes: - traces: - List of trace records as specified by the view parameter. - next_page_token: - If defined, indicates that there are more traces that match - the request and that this value should be passed to the next - request to continue retrieving additional traces. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.ListTracesResponse) - }, -) -_sym_db.RegisterMessage(ListTracesResponse) - -GetTraceRequest = _reflection.GeneratedProtocolMessageType( - "GetTraceRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETTRACEREQUEST, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2", - "__doc__": """The request message for the ``GetTrace`` method. - - Attributes: - project_id: - Required. ID of the Cloud project where the trace data is - stored. - trace_id: - Required. ID of the trace to return. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.GetTraceRequest) - }, -) -_sym_db.RegisterMessage(GetTraceRequest) - -PatchTracesRequest = _reflection.GeneratedProtocolMessageType( - "PatchTracesRequest", - (_message.Message,), - { - "DESCRIPTOR": _PATCHTRACESREQUEST, - "__module__": "google.cloud.devtools.cloudtrace_v1.proto.trace_pb2", - "__doc__": """The request message for the ``PatchTraces`` method. - - Attributes: - project_id: - Required. ID of the Cloud project where the trace data is - stored. - traces: - Required. The body of the message. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.PatchTracesRequest) - }, -) -_sym_db.RegisterMessage(PatchTracesRequest) - - -DESCRIPTOR._options = None -_TRACESPAN_LABELSENTRY._options = None -_TRACESPAN.fields_by_name["parent_span_id"]._options = None -_LISTTRACESREQUEST.fields_by_name["project_id"]._options = None -_LISTTRACESREQUEST.fields_by_name["view"]._options = None -_LISTTRACESREQUEST.fields_by_name["page_size"]._options = None -_LISTTRACESREQUEST.fields_by_name["filter"]._options = None -_LISTTRACESREQUEST.fields_by_name["order_by"]._options = None -_GETTRACEREQUEST.fields_by_name["project_id"]._options = None -_GETTRACEREQUEST.fields_by_name["trace_id"]._options = None -_PATCHTRACESREQUEST.fields_by_name["project_id"]._options = None -_PATCHTRACESREQUEST.fields_by_name["traces"]._options = None - -_TRACESERVICE = _descriptor.ServiceDescriptor( - name="TraceService", - full_name="google.devtools.cloudtrace.v1.TraceService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudtrace.googleapis.com\322A\212\001https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/trace.append,https://www.googleapis.com/auth/trace.readonly", - create_key=_descriptor._internal_create_key, - serialized_start=1517, - serialized_end=2210, - methods=[ - _descriptor.MethodDescriptor( - name="ListTraces", - full_name="google.devtools.cloudtrace.v1.TraceService.ListTraces", - index=0, - containing_service=None, - input_type=_LISTTRACESREQUEST, - output_type=_LISTTRACESRESPONSE, - serialized_options=b'\202\323\344\223\002"\022 /v1/projects/{project_id}/traces\332A\nproject_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetTrace", - full_name="google.devtools.cloudtrace.v1.TraceService.GetTrace", - index=1, - containing_service=None, - input_type=_GETTRACEREQUEST, - output_type=_TRACE, - serialized_options=b"\202\323\344\223\002-\022+/v1/projects/{project_id}/traces/{trace_id}\332A\023project_id,trace_id", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="PatchTraces", - full_name="google.devtools.cloudtrace.v1.TraceService.PatchTraces", - index=2, - containing_service=None, - input_type=_PATCHTRACESREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002*2 /v1/projects/{project_id}/traces:\006traces\332A\021project_id,traces", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_TRACESERVICE) - -DESCRIPTOR.services_by_name["TraceService"] = _TRACESERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/trace_v1/proto/trace_pb2_grpc.py b/google/cloud/trace_v1/proto/trace_pb2_grpc.py deleted file mode 100644 index 1d9141b5..00000000 --- a/google/cloud/trace_v1/proto/trace_pb2_grpc.py +++ /dev/null @@ -1,188 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.trace_v1.proto import ( - trace_pb2 as google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class TraceServiceStub(object): - """This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. Spans for a single trace - may span multiple services. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListTraces = channel.unary_unary( - "/google.devtools.cloudtrace.v1.TraceService/ListTraces", - request_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.ListTracesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.ListTracesResponse.FromString, - ) - self.GetTrace = channel.unary_unary( - "/google.devtools.cloudtrace.v1.TraceService/GetTrace", - request_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.GetTraceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.Trace.FromString, - ) - self.PatchTraces = channel.unary_unary( - "/google.devtools.cloudtrace.v1.TraceService/PatchTraces", - request_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.PatchTracesRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - - -class TraceServiceServicer(object): - """This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. Spans for a single trace - may span multiple services. - """ - - def ListTraces(self, request, context): - """Returns of a list of traces that match the specified filter conditions. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetTrace(self, request, context): - """Gets a single trace by its ID. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def PatchTraces(self, request, context): - """Sends new traces to Stackdriver Trace or updates existing traces. If the ID - of a trace that you send matches that of an existing trace, any fields - in the existing trace and its spans are overwritten by the provided values, - and any new fields provided are merged with the existing trace data. If the - ID does not match, a new trace is created. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_TraceServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListTraces": grpc.unary_unary_rpc_method_handler( - servicer.ListTraces, - request_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.ListTracesRequest.FromString, - response_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.ListTracesResponse.SerializeToString, - ), - "GetTrace": grpc.unary_unary_rpc_method_handler( - servicer.GetTrace, - request_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.GetTraceRequest.FromString, - response_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.Trace.SerializeToString, - ), - "PatchTraces": grpc.unary_unary_rpc_method_handler( - servicer.PatchTraces, - request_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.PatchTracesRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.devtools.cloudtrace.v1.TraceService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class TraceService(object): - """This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. Spans for a single trace - may span multiple services. - """ - - @staticmethod - def ListTraces( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.devtools.cloudtrace.v1.TraceService/ListTraces", - google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.ListTracesRequest.SerializeToString, - google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.ListTracesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetTrace( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.devtools.cloudtrace.v1.TraceService/GetTrace", - google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.GetTraceRequest.SerializeToString, - google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.Trace.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def PatchTraces( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.devtools.cloudtrace.v1.TraceService/PatchTraces", - google_dot_cloud_dot_devtools_dot_cloudtrace__v1_dot_proto_dot_trace__pb2.PatchTracesRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/trace_v1/proto/tracing.proto b/google/cloud/trace_v1/proto/tracing.proto deleted file mode 100644 index fd4f3e02..00000000 --- a/google/cloud/trace_v1/proto/tracing.proto +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.devtools.cloudtrace.v2; - -import "google/api/annotations.proto"; -import "google/devtools/cloudtrace/v2/trace.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/timestamp.proto"; - -option csharp_namespace = "Google.Cloud.Trace.V2"; -option go_package = "google.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace"; -option java_multiple_files = true; -option java_outer_classname = "TracingProto"; -option java_package = "com.google.devtools.cloudtrace.v2"; -option php_namespace = "Google\\Cloud\\Trace\\V2"; - - -// This file describes an API for collecting and viewing traces and spans -// within a trace. A Trace is a collection of spans corresponding to a single -// operation or set of operations for an application. A span is an individual -// timed event which forms a node of the trace tree. A single trace may -// contain span(s) from multiple services. -service TraceService { - // Sends new spans to new or existing traces. You cannot update - // existing spans. - rpc BatchWriteSpans(BatchWriteSpansRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { post: "/v2/{name=projects/*}/traces:batchWrite" body: "*" }; - } - - // Creates a new span. - rpc CreateSpan(Span) returns (Span) { - option (google.api.http) = { post: "/v2/{name=projects/*/traces/*}/spans" body: "*" }; - } -} - -// The request message for the `BatchWriteSpans` method. -message BatchWriteSpansRequest { - // Required. The name of the project where the spans belong. The format is - // `projects/[PROJECT_ID]`. - string name = 1; - - // A list of new spans. The span names must not match existing - // spans, or the results are undefined. - repeated Span spans = 2; -} diff --git a/google/cloud/trace_v1/py.typed b/google/cloud/trace_v1/py.typed new file mode 100644 index 00000000..4717a6c0 --- /dev/null +++ b/google/cloud/trace_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-trace package uses inline types. diff --git a/tests/__init__.py b/google/cloud/trace_v1/services/__init__.py similarity index 90% rename from tests/__init__.py rename to google/cloud/trace_v1/services/__init__.py index ab672909..42ffdf2b 100644 --- a/tests/__init__.py +++ b/google/cloud/trace_v1/services/__init__.py @@ -1,4 +1,6 @@ -# Copyright 2017 Google LLC +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,3 +13,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# diff --git a/google/cloud/trace.py b/google/cloud/trace_v1/services/trace_service/__init__.py similarity index 66% rename from google/cloud/trace.py rename to google/cloud/trace_v1/services/trace_service/__init__.py index 376119a3..e06e796c 100644 --- a/google/cloud/trace.py +++ b/google/cloud/trace_v1/services/trace_service/__init__.py @@ -1,4 +1,6 @@ -# Copyright 2017, Google LLC All rights reserved. +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,11 +13,12 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -from __future__ import absolute_import - -from google.cloud.trace_v2 import TraceServiceClient -from google.cloud.trace_v2 import enums -from google.cloud.trace_v2 import types +from .client import TraceServiceClient +from .async_client import TraceServiceAsyncClient -__all__ = ("enums", "types", "TraceServiceClient") +__all__ = ( + "TraceServiceClient", + "TraceServiceAsyncClient", +) diff --git a/google/cloud/trace_v1/services/trace_service/async_client.py b/google/cloud/trace_v1/services/trace_service/async_client.py new file mode 100644 index 00000000..fb9606b2 --- /dev/null +++ b/google/cloud/trace_v1/services/trace_service/async_client.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v1.services.trace_service import pagers +from google.cloud.trace_v1.types import trace + +from .transports.base import TraceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport +from .client import TraceServiceClient + + +class TraceServiceAsyncClient: + """This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + """ + + _client: TraceServiceClient + + DEFAULT_ENDPOINT = TraceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TraceServiceClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = TraceServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(TraceServiceClient).get_transport_class, type(TraceServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TraceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the trace service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TraceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = TraceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_traces( + self, + request: trace.ListTracesRequest = None, + *, + project_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTracesAsyncPager: + r"""Returns of a list of traces that match the specified + filter conditions. + + Args: + request (:class:`~.trace.ListTracesRequest`): + The request object. The request message for the + `ListTraces` method. All fields are required unless + specified. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListTracesAsyncPager: + The response message for the ``ListTraces`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([project_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = trace.ListTracesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_traces, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=45.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTracesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_trace( + self, + request: trace.GetTraceRequest = None, + *, + project_id: str = None, + trace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trace.Trace: + r"""Gets a single trace by its ID. + + Args: + request (:class:`~.trace.GetTraceRequest`): + The request object. The request message for the + `GetTrace` method. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trace_id (:class:`str`): + Required. ID of the trace to return. + This corresponds to the ``trace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.trace.Trace: + A trace describes how long it takes + for an application to perform an + operation. It consists of a set of + spans, each of which represent a single + timed event within the operation. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([project_id, trace_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = trace.GetTraceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project_id is not None: + request.project_id = project_id + if trace_id is not None: + request.trace_id = trace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_trace, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=45.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def patch_traces( + self, + request: trace.PatchTracesRequest = None, + *, + project_id: str = None, + traces: trace.Traces = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + Args: + request (:class:`~.trace.PatchTracesRequest`): + The request object. The request message for the + `PatchTraces` method. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + traces (:class:`~.trace.Traces`): + Required. The body of the message. + This corresponds to the ``traces`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([project_id, traces]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = trace.PatchTracesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project_id is not None: + request.project_id = project_id + if traces is not None: + request.traces = traces + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.patch_traces, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=45.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-trace",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TraceServiceAsyncClient",) diff --git a/google/cloud/trace_v1/services/trace_service/client.py b/google/cloud/trace_v1/services/trace_service/client.py new file mode 100644 index 00000000..77e2877c --- /dev/null +++ b/google/cloud/trace_v1/services/trace_service/client.py @@ -0,0 +1,470 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v1.services.trace_service import pagers +from google.cloud.trace_v1.types import trace + +from .transports.base import TraceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TraceServiceGrpcTransport +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport + + +class TraceServiceClientMeta(type): + """Metaclass for the TraceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] + _transport_registry["grpc"] = TraceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[TraceServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TraceServiceClient(metaclass=TraceServiceClientMeta): + """This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudtrace.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TraceServiceTransport] = None, + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the trace service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TraceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TraceServiceTransport): + # transport is a TraceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_traces( + self, + request: trace.ListTracesRequest = None, + *, + project_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTracesPager: + r"""Returns of a list of traces that match the specified + filter conditions. + + Args: + request (:class:`~.trace.ListTracesRequest`): + The request object. The request message for the + `ListTraces` method. All fields are required unless + specified. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListTracesPager: + The response message for the ``ListTraces`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a trace.ListTracesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, trace.ListTracesRequest): + request = trace.ListTracesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project_id is not None: + request.project_id = project_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_traces] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTracesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_trace( + self, + request: trace.GetTraceRequest = None, + *, + project_id: str = None, + trace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trace.Trace: + r"""Gets a single trace by its ID. + + Args: + request (:class:`~.trace.GetTraceRequest`): + The request object. The request message for the + `GetTrace` method. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + trace_id (:class:`str`): + Required. ID of the trace to return. + This corresponds to the ``trace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.trace.Trace: + A trace describes how long it takes + for an application to perform an + operation. It consists of a set of + spans, each of which represent a single + timed event within the operation. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, trace_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a trace.GetTraceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, trace.GetTraceRequest): + request = trace.GetTraceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project_id is not None: + request.project_id = project_id + if trace_id is not None: + request.trace_id = trace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_trace] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def patch_traces( + self, + request: trace.PatchTracesRequest = None, + *, + project_id: str = None, + traces: trace.Traces = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + Args: + request (:class:`~.trace.PatchTracesRequest`): + The request object. The request message for the + `PatchTraces` method. + project_id (:class:`str`): + Required. ID of the Cloud project + where the trace data is stored. + This corresponds to the ``project_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + traces (:class:`~.trace.Traces`): + Required. The body of the message. + This corresponds to the ``traces`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project_id, traces]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a trace.PatchTracesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, trace.PatchTracesRequest): + request = trace.PatchTracesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if project_id is not None: + request.project_id = project_id + if traces is not None: + request.traces = traces + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch_traces] + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-trace",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TraceServiceClient",) diff --git a/google/cloud/trace_v1/services/trace_service/pagers.py b/google/cloud/trace_v1/services/trace_service/pagers.py new file mode 100644 index 00000000..f5b2439b --- /dev/null +++ b/google/cloud/trace_v1/services/trace_service/pagers.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.trace_v1.types import trace + + +class ListTracesPager: + """A pager for iterating through ``list_traces`` requests. + + This class thinly wraps an initial + :class:`~.trace.ListTracesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``traces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTraces`` requests and continue to iterate + through the ``traces`` field on the + corresponding responses. + + All the usual :class:`~.trace.ListTracesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., trace.ListTracesResponse], + request: trace.ListTracesRequest, + response: trace.ListTracesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.trace.ListTracesRequest`): + The initial request object. + response (:class:`~.trace.ListTracesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = trace.ListTracesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[trace.ListTracesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[trace.Trace]: + for page in self.pages: + yield from page.traces + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTracesAsyncPager: + """A pager for iterating through ``list_traces`` requests. + + This class thinly wraps an initial + :class:`~.trace.ListTracesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``traces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTraces`` requests and continue to iterate + through the ``traces`` field on the + corresponding responses. + + All the usual :class:`~.trace.ListTracesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[trace.ListTracesResponse]], + request: trace.ListTracesRequest, + response: trace.ListTracesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.trace.ListTracesRequest`): + The initial request object. + response (:class:`~.trace.ListTracesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = trace.ListTracesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[trace.ListTracesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[trace.Trace]: + async def async_generator(): + async for page in self.pages: + for response in page.traces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/trace_v1/services/trace_service/transports/__init__.py b/google/cloud/trace_v1/services/trace_service/transports/__init__.py new file mode 100644 index 00000000..134fa0ad --- /dev/null +++ b/google/cloud/trace_v1/services/trace_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import TraceServiceTransport +from .grpc import TraceServiceGrpcTransport +from .grpc_asyncio import TraceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] +_transport_registry["grpc"] = TraceServiceGrpcTransport +_transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport + + +__all__ = ( + "TraceServiceTransport", + "TraceServiceGrpcTransport", + "TraceServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/trace_v1/services/trace_service/transports/base.py b/google/cloud/trace_v1/services/trace_service/transports/base.py new file mode 100644 index 00000000..b8b99849 --- /dev/null +++ b/google/cloud/trace_v1/services/trace_service/transports/base.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.trace_v1.types import trace +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-trace",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class TraceServiceTransport(abc.ABC): + """Abstract transport class for TraceService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ) + + def __init__( + self, + *, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_traces: gapic_v1.method.wrap_method( + self.list_traces, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=45.0, + client_info=client_info, + ), + self.get_trace: gapic_v1.method.wrap_method( + self.get_trace, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=45.0, + client_info=client_info, + ), + self.patch_traces: gapic_v1.method.wrap_method( + self.patch_traces, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=45.0, + client_info=client_info, + ), + } + + @property + def list_traces( + self, + ) -> typing.Callable[ + [trace.ListTracesRequest], + typing.Union[ + trace.ListTracesResponse, typing.Awaitable[trace.ListTracesResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_trace( + self, + ) -> typing.Callable[ + [trace.GetTraceRequest], + typing.Union[trace.Trace, typing.Awaitable[trace.Trace]], + ]: + raise NotImplementedError() + + @property + def patch_traces( + self, + ) -> typing.Callable[ + [trace.PatchTracesRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + +__all__ = ("TraceServiceTransport",) diff --git a/google/cloud/trace_v1/services/trace_service/transports/grpc.py b/google/cloud/trace_v1/services/trace_service/transports/grpc.py new file mode 100644 index 00000000..998ffea3 --- /dev/null +++ b/google/cloud/trace_v1/services/trace_service/transports/grpc.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.trace_v1.types import trace +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import TraceServiceTransport, DEFAULT_CLIENT_INFO + + +class TraceServiceGrpcTransport(TraceServiceTransport): + """gRPC backend transport for TraceService. + + This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_traces( + self, + ) -> Callable[[trace.ListTracesRequest], trace.ListTracesResponse]: + r"""Return a callable for the list traces method over gRPC. + + Returns of a list of traces that match the specified + filter conditions. + + Returns: + Callable[[~.ListTracesRequest], + ~.ListTracesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_traces" not in self._stubs: + self._stubs["list_traces"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/ListTraces", + request_serializer=trace.ListTracesRequest.serialize, + response_deserializer=trace.ListTracesResponse.deserialize, + ) + return self._stubs["list_traces"] + + @property + def get_trace(self) -> Callable[[trace.GetTraceRequest], trace.Trace]: + r"""Return a callable for the get trace method over gRPC. + + Gets a single trace by its ID. + + Returns: + Callable[[~.GetTraceRequest], + ~.Trace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_trace" not in self._stubs: + self._stubs["get_trace"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/GetTrace", + request_serializer=trace.GetTraceRequest.serialize, + response_deserializer=trace.Trace.deserialize, + ) + return self._stubs["get_trace"] + + @property + def patch_traces(self) -> Callable[[trace.PatchTracesRequest], empty.Empty]: + r"""Return a callable for the patch traces method over gRPC. + + Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + Returns: + Callable[[~.PatchTracesRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "patch_traces" not in self._stubs: + self._stubs["patch_traces"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/PatchTraces", + request_serializer=trace.PatchTracesRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["patch_traces"] + + +__all__ = ("TraceServiceGrpcTransport",) diff --git a/google/cloud/trace_v1/services/trace_service/transports/grpc_asyncio.py b/google/cloud/trace_v1/services/trace_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..7ebc87d4 --- /dev/null +++ b/google/cloud/trace_v1/services/trace_service/transports/grpc_asyncio.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.trace_v1.types import trace +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import TraceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TraceServiceGrpcTransport + + +class TraceServiceGrpcAsyncIOTransport(TraceServiceTransport): + """gRPC AsyncIO backend transport for TraceService. + + This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. Spans for a single trace may span + multiple services. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_traces( + self, + ) -> Callable[[trace.ListTracesRequest], Awaitable[trace.ListTracesResponse]]: + r"""Return a callable for the list traces method over gRPC. + + Returns of a list of traces that match the specified + filter conditions. + + Returns: + Callable[[~.ListTracesRequest], + Awaitable[~.ListTracesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_traces" not in self._stubs: + self._stubs["list_traces"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/ListTraces", + request_serializer=trace.ListTracesRequest.serialize, + response_deserializer=trace.ListTracesResponse.deserialize, + ) + return self._stubs["list_traces"] + + @property + def get_trace(self) -> Callable[[trace.GetTraceRequest], Awaitable[trace.Trace]]: + r"""Return a callable for the get trace method over gRPC. + + Gets a single trace by its ID. + + Returns: + Callable[[~.GetTraceRequest], + Awaitable[~.Trace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_trace" not in self._stubs: + self._stubs["get_trace"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/GetTrace", + request_serializer=trace.GetTraceRequest.serialize, + response_deserializer=trace.Trace.deserialize, + ) + return self._stubs["get_trace"] + + @property + def patch_traces( + self, + ) -> Callable[[trace.PatchTracesRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the patch traces method over gRPC. + + Sends new traces to Stackdriver Trace or updates + existing traces. If the ID of a trace that you send + matches that of an existing trace, any fields in the + existing trace and its spans are overwritten by the + provided values, and any new fields provided are merged + with the existing trace data. If the ID does not match, + a new trace is created. + + Returns: + Callable[[~.PatchTracesRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "patch_traces" not in self._stubs: + self._stubs["patch_traces"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v1.TraceService/PatchTraces", + request_serializer=trace.PatchTracesRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["patch_traces"] + + +__all__ = ("TraceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/trace_v1/types.py b/google/cloud/trace_v1/types.py deleted file mode 100644 index 07c3af3b..00000000 --- a/google/cloud/trace_v1/types.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.trace_v1.proto import trace_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 - - -_shared_modules = [ - empty_pb2, - timestamp_pb2, -] - -_local_modules = [ - trace_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.trace_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/trace_v1/types/__init__.py b/google/cloud/trace_v1/types/__init__.py new file mode 100644 index 00000000..66dbf851 --- /dev/null +++ b/google/cloud/trace_v1/types/__init__.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .trace import ( + Trace, + Traces, + TraceSpan, + ListTracesRequest, + ListTracesResponse, + GetTraceRequest, + PatchTracesRequest, +) + + +__all__ = ( + "Trace", + "Traces", + "TraceSpan", + "ListTracesRequest", + "ListTracesResponse", + "GetTraceRequest", + "PatchTracesRequest", +) diff --git a/google/cloud/trace_v1/types/trace.py b/google/cloud/trace_v1/types/trace.py new file mode 100644 index 00000000..81cfbc93 --- /dev/null +++ b/google/cloud/trace_v1/types/trace.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.devtools.cloudtrace.v1", + manifest={ + "Trace", + "Traces", + "TraceSpan", + "ListTracesRequest", + "ListTracesResponse", + "GetTraceRequest", + "PatchTracesRequest", + }, +) + + +class Trace(proto.Message): + r"""A trace describes how long it takes for an application to + perform an operation. It consists of a set of spans, each of + which represent a single timed event within the operation. + + Attributes: + project_id (str): + Project ID of the Cloud project where the + trace data is stored. + trace_id (str): + Globally unique identifier for the trace. This identifier is + a 128-bit numeric value formatted as a 32-byte hex string. + For example, ``382d4f4c6b7bb2f4a972559d9085001d``. + spans (Sequence[~.trace.TraceSpan]): + Collection of spans in the trace. + """ + + project_id = proto.Field(proto.STRING, number=1) + + trace_id = proto.Field(proto.STRING, number=2) + + spans = proto.RepeatedField(proto.MESSAGE, number=3, message="TraceSpan",) + + +class Traces(proto.Message): + r"""List of new or updated traces. + + Attributes: + traces (Sequence[~.trace.Trace]): + List of traces. + """ + + traces = proto.RepeatedField(proto.MESSAGE, number=1, message=Trace,) + + +class TraceSpan(proto.Message): + r"""A span represents a single timed event within a trace. Spans + can be nested and form a trace tree. Often, a trace contains a + root span that describes the end-to-end latency of an operation + and, optionally, one or more subspans for its suboperations. + Spans do not need to be contiguous. There may be gaps between + spans in a trace. + + Attributes: + span_id (int): + Identifier for the span. Must be a 64-bit integer other than + 0 and unique within a trace. For example, + ``2205310701640571284``. + kind (~.trace.TraceSpan.SpanKind): + Distinguishes between spans generated in a particular + context. For example, two spans with the same name may be + distinguished using ``RPC_CLIENT`` and ``RPC_SERVER`` to + identify queueing latency associated with the span. + name (str): + Name of the span. Must be less than 128 + bytes. The span name is sanitized and displayed + in the Stackdriver Trace tool in the Google + Cloud Platform Console. + The name may be a method name or some other per- + call site name. For the same executable and the + same call point, a best practice is to use a + consistent name, which makes it easier to + correlate cross-trace spans. + start_time (~.timestamp.Timestamp): + Start time of the span in nanoseconds from + the UNIX epoch. + end_time (~.timestamp.Timestamp): + End time of the span in nanoseconds from the + UNIX epoch. + parent_span_id (int): + Optional. ID of the parent span, if any. + labels (Sequence[~.trace.TraceSpan.LabelsEntry]): + Collection of labels associated with the span. Label keys + must be less than 128 bytes. Label values must be less than + 16 kilobytes (10MB for ``/stacktrace`` values). + + Some predefined label keys exist, or you may create your + own. When creating your own, we recommend the following + formats: + + - ``/category/product/key`` for agents of well-known + products (e.g. ``/db/mongodb/read_size``). + - ``short_host/path/key`` for domain-specific keys (e.g. + ``foo.com/myproduct/bar``) + + Predefined labels include: + + - ``/agent`` + - ``/component`` + - ``/error/message`` + - ``/error/name`` + - ``/http/client_city`` + - ``/http/client_country`` + - ``/http/client_protocol`` + - ``/http/client_region`` + - ``/http/host`` + - ``/http/method`` + - ``/http/path`` + - ``/http/redirected_url`` + - ``/http/request/size`` + - ``/http/response/size`` + - ``/http/route`` + - ``/http/status_code`` + - ``/http/url`` + - ``/http/user_agent`` + - ``/pid`` + - ``/stacktrace`` + - ``/tid`` + """ + + class SpanKind(proto.Enum): + r"""Type of span. Can be used to specify additional relationships + between spans in addition to a parent/child relationship. + """ + SPAN_KIND_UNSPECIFIED = 0 + RPC_SERVER = 1 + RPC_CLIENT = 2 + + span_id = proto.Field(proto.FIXED64, number=1) + + kind = proto.Field(proto.ENUM, number=2, enum=SpanKind,) + + name = proto.Field(proto.STRING, number=3) + + start_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + parent_span_id = proto.Field(proto.FIXED64, number=6) + + labels = proto.MapField(proto.STRING, proto.STRING, number=7) + + +class ListTracesRequest(proto.Message): + r"""The request message for the ``ListTraces`` method. All fields are + required unless specified. + + Attributes: + project_id (str): + Required. ID of the Cloud project where the + trace data is stored. + view (~.trace.ListTracesRequest.ViewType): + Optional. Type of data returned for traces in the list. + Default is ``MINIMAL``. + page_size (int): + Optional. Maximum number of traces to return. + If not specified or <= 0, the implementation + selects a reasonable value. The implementation + may return fewer traces than the requested page + size. + page_token (str): + Token identifying the page of results to return. If + provided, use the value of the ``next_page_token`` field + from a previous request. + start_time (~.timestamp.Timestamp): + Start of the time interval (inclusive) during + which the trace data was collected from the + application. + end_time (~.timestamp.Timestamp): + End of the time interval (inclusive) during + which the trace data was collected from the + application. + filter (str): + Optional. A filter against labels for the request. + + By default, searches use prefix matching. To specify exact + match, prepend a plus symbol (``+``) to the search term. + Multiple terms are ANDed. Syntax: + + - ``root:NAME_PREFIX`` or ``NAME_PREFIX``: Return traces + where any root span starts with ``NAME_PREFIX``. + - ``+root:NAME`` or ``+NAME``: Return traces where any root + span's name is exactly ``NAME``. + - ``span:NAME_PREFIX``: Return traces where any span starts + with ``NAME_PREFIX``. + - ``+span:NAME``: Return traces where any span's name is + exactly ``NAME``. + - ``latency:DURATION``: Return traces whose overall latency + is greater or equal to than ``DURATION``. Accepted units + are nanoseconds (``ns``), milliseconds (``ms``), and + seconds (``s``). Default is ``ms``. For example, + ``latency:24ms`` returns traces whose overall latency is + greater than or equal to 24 milliseconds. + - ``label:LABEL_KEY``: Return all traces containing the + specified label key (exact match, case-sensitive) + regardless of the key:value pair's value (including empty + values). + - ``LABEL_KEY:VALUE_PREFIX``: Return all traces containing + the specified label key (exact match, case-sensitive) + whose value starts with ``VALUE_PREFIX``. Both a key and + a value must be specified. + - ``+LABEL_KEY:VALUE``: Return all traces containing a + key:value pair exactly matching the specified text. Both + a key and a value must be specified. + - ``method:VALUE``: Equivalent to ``/http/method:VALUE``. + - ``url:VALUE``: Equivalent to ``/http/url:VALUE``. + order_by (str): + Optional. Field used to sort the returned traces. Can be one + of the following: + + - ``trace_id`` + - ``name`` (``name`` field of root span in the trace) + - ``duration`` (difference between ``end_time`` and + ``start_time`` fields of the root span) + - ``start`` (``start_time`` field of the root span) + + Descending order can be specified by appending ``desc`` to + the sort field (for example, ``name desc``). + + Only one sort field is permitted. + """ + + class ViewType(proto.Enum): + r"""Type of data returned for traces in the list.""" + VIEW_TYPE_UNSPECIFIED = 0 + MINIMAL = 1 + ROOTSPAN = 2 + COMPLETE = 3 + + project_id = proto.Field(proto.STRING, number=1) + + view = proto.Field(proto.ENUM, number=2, enum=ViewType,) + + page_size = proto.Field(proto.INT32, number=3) + + page_token = proto.Field(proto.STRING, number=4) + + start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + + filter = proto.Field(proto.STRING, number=7) + + order_by = proto.Field(proto.STRING, number=8) + + +class ListTracesResponse(proto.Message): + r"""The response message for the ``ListTraces`` method. + + Attributes: + traces (Sequence[~.trace.Trace]): + List of trace records as specified by the + view parameter. + next_page_token (str): + If defined, indicates that there are more + traces that match the request and that this + value should be passed to the next request to + continue retrieving additional traces. + """ + + @property + def raw_page(self): + return self + + traces = proto.RepeatedField(proto.MESSAGE, number=1, message=Trace,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetTraceRequest(proto.Message): + r"""The request message for the ``GetTrace`` method. + + Attributes: + project_id (str): + Required. ID of the Cloud project where the + trace data is stored. + trace_id (str): + Required. ID of the trace to return. + """ + + project_id = proto.Field(proto.STRING, number=1) + + trace_id = proto.Field(proto.STRING, number=2) + + +class PatchTracesRequest(proto.Message): + r"""The request message for the ``PatchTraces`` method. + + Attributes: + project_id (str): + Required. ID of the Cloud project where the + trace data is stored. + traces (~.trace.Traces): + Required. The body of the message. + """ + + project_id = proto.Field(proto.STRING, number=1) + + traces = proto.Field(proto.MESSAGE, number=2, message=Traces,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/trace_v2/__init__.py b/google/cloud/trace_v2/__init__.py index e984b7b6..518583ba 100644 --- a/google/cloud/trace_v2/__init__.py +++ b/google/cloud/trace_v2/__init__.py @@ -1,45 +1,35 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.trace_v2 import types -from google.cloud.trace_v2.gapic import enums -from google.cloud.trace_v2.gapic import trace_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class TraceServiceClient(trace_service_client.TraceServiceClient): - __doc__ = trace_service_client.TraceServiceClient.__doc__ - enums = enums +from .services.trace_service import TraceServiceClient +from .types.trace import AttributeValue +from .types.trace import Module +from .types.trace import Span +from .types.trace import StackTrace +from .types.trace import TruncatableString +from .types.tracing import BatchWriteSpansRequest __all__ = ( - "enums", - "types", + "AttributeValue", + "BatchWriteSpansRequest", + "Module", + "Span", + "StackTrace", + "TruncatableString", "TraceServiceClient", ) diff --git a/google/cloud/trace_v2/gapic/__init__.py b/google/cloud/trace_v2/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/trace_v2/gapic/enums.py b/google/cloud/trace_v2/gapic/enums.py deleted file mode 100644 index 36c3f13d..00000000 --- a/google/cloud/trace_v2/gapic/enums.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class Span(object): - class SpanKind(enum.IntEnum): - """ - Type of span. Can be used to specify additional relationships between spans - in addition to a parent/child relationship. - - Attributes: - SPAN_KIND_UNSPECIFIED (int): Unspecified. Do NOT use as default. - Implementations MAY assume SpanKind.INTERNAL to be default. - INTERNAL (int): Indicates that the span is used internally. Default value. - SERVER (int): Indicates that the span covers server-side handling of an RPC or other - remote network request. - CLIENT (int): Indicates that the span covers the client-side wrapper around an RPC or - other remote request. - PRODUCER (int): Indicates that the span describes producer sending a message to a broker. - Unlike client and server, there is no direct critical path latency - relationship between producer and consumer spans (e.g. publishing a - message to a pubsub service). - CONSUMER (int): Indicates that the span describes consumer receiving a message from a - broker. Unlike client and server, there is no direct critical path - latency relationship between producer and consumer spans (e.g. receiving - a message from a pubsub service subscription). - """ - - SPAN_KIND_UNSPECIFIED = 0 - INTERNAL = 1 - SERVER = 2 - CLIENT = 3 - PRODUCER = 4 - CONSUMER = 5 - - class TimeEvent(object): - class MessageEvent(object): - class Type(enum.IntEnum): - """ - Indicates whether the message was sent or received. - - Attributes: - TYPE_UNSPECIFIED (int): Unknown event type. - SENT (int): Indicates a sent message. - RECEIVED (int): Indicates a received message. - """ - - TYPE_UNSPECIFIED = 0 - SENT = 1 - RECEIVED = 2 - - class Link(object): - class Type(enum.IntEnum): - """ - The relationship of the current span relative to the linked span: child, - parent, or unspecified. - - Attributes: - TYPE_UNSPECIFIED (int): The relationship of the two spans is unknown. - CHILD_LINKED_SPAN (int): The linked span is a child of the current span. - PARENT_LINKED_SPAN (int): The linked span is a parent of the current span. - """ - - TYPE_UNSPECIFIED = 0 - CHILD_LINKED_SPAN = 1 - PARENT_LINKED_SPAN = 2 diff --git a/google/cloud/trace_v2/gapic/trace_service_client.py b/google/cloud/trace_v2/gapic/trace_service_client.py deleted file mode 100644 index 952c2f8a..00000000 --- a/google/cloud/trace_v2/gapic/trace_service_client.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.devtools.cloudtrace.v2 TraceService API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.path_template -import grpc - -from google.cloud.trace_v2.gapic import enums -from google.cloud.trace_v2.gapic import trace_service_client_config -from google.cloud.trace_v2.gapic.transports import trace_service_grpc_transport -from google.cloud.trace_v2.proto import trace_pb2 -from google.cloud.trace_v2.proto import tracing_pb2 -from google.cloud.trace_v2.proto import tracing_pb2_grpc -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 -from google.protobuf import wrappers_pb2 -from google.rpc import status_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-trace",).version - - -class TraceServiceClient(object): - """ - This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. A single trace may - contain span(s) from multiple services. - """ - - SERVICE_ADDRESS = "cloudtrace.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.devtools.cloudtrace.v2.TraceService" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - TraceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def project_path(cls, project): - """Return a fully-qualified project string.""" - return google.api_core.path_template.expand( - "projects/{project}", project=project, - ) - - @classmethod - def span_path(cls, project, trace, span): - """Return a fully-qualified span string.""" - return google.api_core.path_template.expand( - "projects/{project}/traces/{trace}/spans/{span}", - project=project, - trace=trace, - span=span, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.TraceServiceGrpcTransport, - Callable[[~.Credentials, type], ~.TraceServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = trace_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=trace_service_grpc_transport.TraceServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = trace_service_grpc_transport.TraceServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def create_span( - self, - name, - span_id, - display_name, - start_time, - end_time, - parent_span_id=None, - attributes=None, - stack_trace=None, - time_events=None, - links=None, - status=None, - same_process_as_parent_span=None, - child_span_count=None, - span_kind=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a new span. - - Example: - >>> from google.cloud import trace_v2 - >>> - >>> client = trace_v2.TraceServiceClient() - >>> - >>> name = client.span_path('[PROJECT]', '[TRACE]', '[SPAN]') - >>> - >>> # TODO: Initialize `span_id`: - >>> span_id = '' - >>> - >>> # TODO: Initialize `display_name`: - >>> display_name = {} - >>> - >>> # TODO: Initialize `start_time`: - >>> start_time = {} - >>> - >>> # TODO: Initialize `end_time`: - >>> end_time = {} - >>> - >>> response = client.create_span(name, span_id, display_name, start_time, end_time) - - Args: - name (str): Required. The resource name of the span in the following format: - - :: - - projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] - - [TRACE_ID] is a unique identifier for a trace within a project; it is a - 32-character hexadecimal encoding of a 16-byte array. - - [SPAN_ID] is a unique identifier for a span within a trace; it is a - 16-character hexadecimal encoding of an 8-byte array. - span_id (str): Required. The [SPAN_ID] portion of the span's resource name. - display_name (Union[dict, ~google.cloud.trace_v2.types.TruncatableString]): Required. A description of the span's operation (up to 128 bytes). - Stackdriver Trace displays the description in the - Google Cloud Platform Console. - For example, the display name can be a qualified method name or a file name - and a line number where the operation is called. A best practice is to use - the same display name within an application and at the same call point. - This makes it easier to correlate spans in different traces. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.TruncatableString` - start_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): Required. The start time of the span. On the client side, this is the time kept by - the local machine where the span execution starts. On the server side, this - is the time when the server's application handler starts running. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.Timestamp` - end_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): Required. The end time of the span. On the client side, this is the time kept by - the local machine where the span execution ends. On the server side, this - is the time when the server application handler stops running. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.Timestamp` - parent_span_id (str): The [SPAN_ID] of this span's parent span. If this is a root span, - then this field must be empty. - attributes (Union[dict, ~google.cloud.trace_v2.types.Attributes]): A set of attributes on the span. You can have up to 32 attributes per - span. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.Attributes` - stack_trace (Union[dict, ~google.cloud.trace_v2.types.StackTrace]): Stack trace captured at the start of the span. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.StackTrace` - time_events (Union[dict, ~google.cloud.trace_v2.types.TimeEvents]): A set of time events. You can have up to 32 annotations and 128 message - events per span. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.TimeEvents` - links (Union[dict, ~google.cloud.trace_v2.types.Links]): Links associated with the span. You can have up to 128 links per Span. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.Links` - status (Union[dict, ~google.cloud.trace_v2.types.Status]): Optional. The final status for this span. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.Status` - same_process_as_parent_span (Union[dict, ~google.cloud.trace_v2.types.BoolValue]): Optional. Set this parameter to indicate whether this span is in - the same process as its parent. If you do not set this parameter, - Stackdriver Trace is unable to take advantage of this helpful - information. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.BoolValue` - child_span_count (Union[dict, ~google.cloud.trace_v2.types.Int32Value]): Optional. The number of child spans that were generated while this span - was active. If set, allows implementation to detect missing child spans. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.Int32Value` - span_kind (~google.cloud.trace_v2.types.SpanKind): Optional. Distinguishes between spans generated in a particular - context. For example, two spans with the same name may be distinguished - using ``CLIENT`` (caller) and ``SERVER`` (callee) to identify an RPC - call. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.trace_v2.types.Span` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_span" not in self._inner_api_calls: - self._inner_api_calls[ - "create_span" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_span, - default_retry=self._method_configs["CreateSpan"].retry, - default_timeout=self._method_configs["CreateSpan"].timeout, - client_info=self._client_info, - ) - - request = trace_pb2.Span( - name=name, - span_id=span_id, - display_name=display_name, - start_time=start_time, - end_time=end_time, - parent_span_id=parent_span_id, - attributes=attributes, - stack_trace=stack_trace, - time_events=time_events, - links=links, - status=status, - same_process_as_parent_span=same_process_as_parent_span, - child_span_count=child_span_count, - span_kind=span_kind, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_span"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def batch_write_spans( - self, - name, - spans, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sends new spans to new or existing traces. You cannot update - existing spans. - - Example: - >>> from google.cloud import trace_v2 - >>> - >>> client = trace_v2.TraceServiceClient() - >>> - >>> name = client.project_path('[PROJECT]') - >>> - >>> # TODO: Initialize `spans`: - >>> spans = [] - >>> - >>> client.batch_write_spans(name, spans) - - Args: - name (str): Required. The name of the project where the spans belong. The format - is ``projects/[PROJECT_ID]``. - spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): Required. A list of new spans. The span names must not match existing - spans, or the results are undefined. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.trace_v2.types.Span` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_write_spans" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_write_spans" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_write_spans, - default_retry=self._method_configs["BatchWriteSpans"].retry, - default_timeout=self._method_configs["BatchWriteSpans"].timeout, - client_info=self._client_info, - ) - - request = tracing_pb2.BatchWriteSpansRequest(name=name, spans=spans,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["batch_write_spans"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/trace_v2/gapic/trace_service_client_config.py b/google/cloud/trace_v2/gapic/trace_service_client_config.py deleted file mode 100644 index bbc1d8f5..00000000 --- a/google/cloud/trace_v2/gapic/trace_service_client_config.py +++ /dev/null @@ -1,52 +0,0 @@ -config = { - "interfaces": { - "google.devtools.cloudtrace.v2.TraceService": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.2, - "max_retry_delay_millis": 1000, - "initial_rpc_timeout_millis": 120000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 120000, - "total_timeout_millis": 120000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 120000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 120000, - "total_timeout_millis": 120000, - }, - }, - "methods": { - "CreateSpan": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "BatchWriteSpans": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - }, - } - } -} diff --git a/google/cloud/trace_v2/gapic/transports/__init__.py b/google/cloud/trace_v2/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/trace_v2/gapic/transports/trace_service_grpc_transport.py b/google/cloud/trace_v2/gapic/transports/trace_service_grpc_transport.py deleted file mode 100644 index b1ee511c..00000000 --- a/google/cloud/trace_v2/gapic/transports/trace_service_grpc_transport.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.trace_v2.proto import tracing_pb2_grpc - - -class TraceServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.devtools.cloudtrace.v2 TraceService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/trace.append", - ) - - def __init__( - self, channel=None, credentials=None, address="cloudtrace.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "trace_service_stub": tracing_pb2_grpc.TraceServiceStub(channel), - } - - @classmethod - def create_channel( - cls, address="cloudtrace.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def create_span(self): - """Return the gRPC stub for :meth:`TraceServiceClient.create_span`. - - Creates a new span. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["trace_service_stub"].CreateSpan - - @property - def batch_write_spans(self): - """Return the gRPC stub for :meth:`TraceServiceClient.batch_write_spans`. - - Sends new spans to new or existing traces. You cannot update - existing spans. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["trace_service_stub"].BatchWriteSpans diff --git a/google/cloud/trace_v2/proto/__init__.py b/google/cloud/trace_v2/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/trace_v2/proto/trace.proto b/google/cloud/trace_v2/proto/trace.proto deleted file mode 100644 index 66669aa6..00000000 --- a/google/cloud/trace_v2/proto/trace.proto +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright 2020 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.devtools.cloudtrace.v2; - -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/protobuf/timestamp.proto"; -import "google/protobuf/wrappers.proto"; -import "google/rpc/status.proto"; -import "google/api/annotations.proto"; - -option csharp_namespace = "Google.Cloud.Trace.V2"; -option go_package = "google.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace"; -option java_multiple_files = true; -option java_outer_classname = "TraceProto"; -option java_package = "com.google.devtools.cloudtrace.v2"; -option php_namespace = "Google\\Cloud\\Trace\\V2"; -option ruby_package = "Google::Cloud::Trace::V2"; - -// A span represents a single operation within a trace. Spans can be -// nested to form a trace tree. Often, a trace contains a root span -// that describes the end-to-end latency, and one or more subspans for -// its sub-operations. A trace can also contain multiple root spans, -// or none at all. Spans do not need to be contiguous—there may be -// gaps or overlaps between spans in a trace. -message Span { - option (google.api.resource) = { - type: "cloudtrace.googleapis.com/Span" - pattern: "projects/{project}/traces/{trace}/spans/{span}" - }; - - // A set of attributes, each in the format `[KEY]:[VALUE]`. - message Attributes { - // The set of attributes. Each attribute's key can be up to 128 bytes - // long. The value can be a string up to 256 bytes, a signed 64-bit integer, - // or the Boolean values `true` and `false`. For example: - // - // "/instance_id": { "string_value": { "value": "my-instance" } } - // "/http/request_bytes": { "int_value": 300 } - // "abc.com/myattribute": { "bool_value": false } - map attribute_map = 1; - - // The number of attributes that were discarded. Attributes can be discarded - // because their keys are too long or because there are too many attributes. - // If this value is 0 then all attributes are valid. - int32 dropped_attributes_count = 2; - } - - // A time-stamped annotation or message event in the Span. - message TimeEvent { - // Text annotation with a set of attributes. - message Annotation { - // A user-supplied message describing the event. The maximum length for - // the description is 256 bytes. - TruncatableString description = 1; - - // A set of attributes on the annotation. You can have up to 4 attributes - // per Annotation. - Attributes attributes = 2; - } - - // An event describing a message sent/received between Spans. - message MessageEvent { - // Indicates whether the message was sent or received. - enum Type { - // Unknown event type. - TYPE_UNSPECIFIED = 0; - - // Indicates a sent message. - SENT = 1; - - // Indicates a received message. - RECEIVED = 2; - } - - // Type of MessageEvent. Indicates whether the message was sent or - // received. - Type type = 1; - - // An identifier for the MessageEvent's message that can be used to match - // SENT and RECEIVED MessageEvents. It is recommended to be unique within - // a Span. - int64 id = 2; - - // The number of uncompressed bytes sent or received. - int64 uncompressed_size_bytes = 3; - - // The number of compressed bytes sent or received. If missing assumed to - // be the same size as uncompressed. - int64 compressed_size_bytes = 4; - } - - // The timestamp indicating the time the event occurred. - google.protobuf.Timestamp time = 1; - - // A `TimeEvent` can contain either an `Annotation` object or a - // `MessageEvent` object, but not both. - oneof value { - // Text annotation with a set of attributes. - Annotation annotation = 2; - - // An event describing a message sent/received between Spans. - MessageEvent message_event = 3; - } - } - - // A collection of `TimeEvent`s. A `TimeEvent` is a time-stamped annotation - // on the span, consisting of either user-supplied key:value pairs, or - // details of a message sent/received between Spans. - message TimeEvents { - // A collection of `TimeEvent`s. - repeated TimeEvent time_event = 1; - - // The number of dropped annotations in all the included time events. - // If the value is 0, then no annotations were dropped. - int32 dropped_annotations_count = 2; - - // The number of dropped message events in all the included time events. - // If the value is 0, then no message events were dropped. - int32 dropped_message_events_count = 3; - } - - // A pointer from the current span to another span in the same trace or in a - // different trace. For example, this can be used in batching operations, - // where a single batch handler processes multiple requests from different - // traces or when the handler receives a request from a different project. - message Link { - // The relationship of the current span relative to the linked span: child, - // parent, or unspecified. - enum Type { - // The relationship of the two spans is unknown. - TYPE_UNSPECIFIED = 0; - - // The linked span is a child of the current span. - CHILD_LINKED_SPAN = 1; - - // The linked span is a parent of the current span. - PARENT_LINKED_SPAN = 2; - } - - // The [TRACE_ID] for a trace within a project. - string trace_id = 1; - - // The [SPAN_ID] for a span within a trace. - string span_id = 2; - - // The relationship of the current span relative to the linked span. - Type type = 3; - - // A set of attributes on the link. You have have up to 32 attributes per - // link. - Attributes attributes = 4; - } - - // A collection of links, which are references from this span to a span - // in the same or different trace. - message Links { - // A collection of links. - repeated Link link = 1; - - // The number of dropped links after the maximum size was enforced. If - // this value is 0, then no links were dropped. - int32 dropped_links_count = 2; - } - - // Type of span. Can be used to specify additional relationships between spans - // in addition to a parent/child relationship. - enum SpanKind { - // Unspecified. Do NOT use as default. - // Implementations MAY assume SpanKind.INTERNAL to be default. - SPAN_KIND_UNSPECIFIED = 0; - - // Indicates that the span is used internally. Default value. - INTERNAL = 1; - - // Indicates that the span covers server-side handling of an RPC or other - // remote network request. - SERVER = 2; - - // Indicates that the span covers the client-side wrapper around an RPC or - // other remote request. - CLIENT = 3; - - // Indicates that the span describes producer sending a message to a broker. - // Unlike client and server, there is no direct critical path latency - // relationship between producer and consumer spans (e.g. publishing a - // message to a pubsub service). - PRODUCER = 4; - - // Indicates that the span describes consumer receiving a message from a - // broker. Unlike client and server, there is no direct critical path - // latency relationship between producer and consumer spans (e.g. receiving - // a message from a pubsub service subscription). - CONSUMER = 5; - } - - // Required. The resource name of the span in the following format: - // - // projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] - // - // [TRACE_ID] is a unique identifier for a trace within a project; - // it is a 32-character hexadecimal encoding of a 16-byte array. - // - // [SPAN_ID] is a unique identifier for a span within a trace; it - // is a 16-character hexadecimal encoding of an 8-byte array. - string name = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. The [SPAN_ID] portion of the span's resource name. - string span_id = 2 [(google.api.field_behavior) = REQUIRED]; - - // The [SPAN_ID] of this span's parent span. If this is a root span, - // then this field must be empty. - string parent_span_id = 3; - - // Required. A description of the span's operation (up to 128 bytes). - // Stackdriver Trace displays the description in the - // Google Cloud Platform Console. - // For example, the display name can be a qualified method name or a file name - // and a line number where the operation is called. A best practice is to use - // the same display name within an application and at the same call point. - // This makes it easier to correlate spans in different traces. - TruncatableString display_name = 4 [(google.api.field_behavior) = REQUIRED]; - - // Required. The start time of the span. On the client side, this is the time kept by - // the local machine where the span execution starts. On the server side, this - // is the time when the server's application handler starts running. - google.protobuf.Timestamp start_time = 5 [(google.api.field_behavior) = REQUIRED]; - - // Required. The end time of the span. On the client side, this is the time kept by - // the local machine where the span execution ends. On the server side, this - // is the time when the server application handler stops running. - google.protobuf.Timestamp end_time = 6 [(google.api.field_behavior) = REQUIRED]; - - // A set of attributes on the span. You can have up to 32 attributes per - // span. - Attributes attributes = 7; - - // Stack trace captured at the start of the span. - StackTrace stack_trace = 8; - - // A set of time events. You can have up to 32 annotations and 128 message - // events per span. - TimeEvents time_events = 9; - - // Links associated with the span. You can have up to 128 links per Span. - Links links = 10; - - // Optional. The final status for this span. - google.rpc.Status status = 11 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Set this parameter to indicate whether this span is in - // the same process as its parent. If you do not set this parameter, - // Stackdriver Trace is unable to take advantage of this helpful - // information. - google.protobuf.BoolValue same_process_as_parent_span = 12 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The number of child spans that were generated while this span - // was active. If set, allows implementation to detect missing child spans. - google.protobuf.Int32Value child_span_count = 13 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. Distinguishes between spans generated in a particular context. For example, - // two spans with the same name may be distinguished using `CLIENT` (caller) - // and `SERVER` (callee) to identify an RPC call. - SpanKind span_kind = 14 [(google.api.field_behavior) = OPTIONAL]; -} - -// The allowed types for [VALUE] in a `[KEY]:[VALUE]` attribute. -message AttributeValue { - // The type of the value. - oneof value { - // A string up to 256 bytes long. - TruncatableString string_value = 1; - - // A 64-bit signed integer. - int64 int_value = 2; - - // A Boolean value represented by `true` or `false`. - bool bool_value = 3; - } -} - -// A call stack appearing in a trace. -message StackTrace { - // Represents a single stack frame in a stack trace. - message StackFrame { - // The fully-qualified name that uniquely identifies the function or - // method that is active in this frame (up to 1024 bytes). - TruncatableString function_name = 1; - - // An un-mangled function name, if `function_name` is - // [mangled](http://www.avabodh.com/cxxin/namemangling.html). The name can - // be fully-qualified (up to 1024 bytes). - TruncatableString original_function_name = 2; - - // The name of the source file where the function call appears (up to 256 - // bytes). - TruncatableString file_name = 3; - - // The line number in `file_name` where the function call appears. - int64 line_number = 4; - - // The column number where the function call appears, if available. - // This is important in JavaScript because of its anonymous functions. - int64 column_number = 5; - - // The binary module from where the code was loaded. - Module load_module = 6; - - // The version of the deployed source code (up to 128 bytes). - TruncatableString source_version = 7; - } - - // A collection of stack frames, which can be truncated. - message StackFrames { - // Stack frames in this call stack. - repeated StackFrame frame = 1; - - // The number of stack frames that were dropped because there - // were too many stack frames. - // If this value is 0, then no stack frames were dropped. - int32 dropped_frames_count = 2; - } - - // Stack frames in this stack trace. A maximum of 128 frames are allowed. - StackFrames stack_frames = 1; - - // The hash ID is used to conserve network bandwidth for duplicate - // stack traces within a single trace. - // - // Often multiple spans will have identical stack traces. - // The first occurrence of a stack trace should contain both the - // `stackFrame` content and a value in `stackTraceHashId`. - // - // Subsequent spans within the same request can refer - // to that stack trace by only setting `stackTraceHashId`. - int64 stack_trace_hash_id = 2; -} - -// Binary module. -message Module { - // For example: main binary, kernel modules, and dynamic libraries - // such as libc.so, sharedlib.so (up to 256 bytes). - TruncatableString module = 1; - - // A unique identifier for the module, usually a hash of its - // contents (up to 128 bytes). - TruncatableString build_id = 2; -} - -// Represents a string that might be shortened to a specified length. -message TruncatableString { - // The shortened string. For example, if the original string is 500 - // bytes long and the limit of the string is 128 bytes, then - // `value` contains the first 128 bytes of the 500-byte string. - // - // Truncation always happens on a UTF8 character boundary. If there - // are multi-byte characters in the string, then the length of the - // shortened string might be less than the size limit. - string value = 1; - - // The number of bytes removed from the original string. If this - // value is 0, then the string was not shortened. - int32 truncated_byte_count = 2; -} diff --git a/google/cloud/trace_v2/proto/trace_pb2.py b/google/cloud/trace_v2/proto/trace_pb2.py deleted file mode 100644 index f32eab3d..00000000 --- a/google/cloud/trace_v2/proto/trace_pb2.py +++ /dev/null @@ -1,2081 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/devtools/cloudtrace_v2/proto/trace.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/devtools/cloudtrace_v2/proto/trace.proto", - package="google.devtools.cloudtrace.v2", - syntax="proto3", - serialized_options=b"\n!com.google.devtools.cloudtrace.v2B\nTraceProtoP\001ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace\252\002\025Google.Cloud.Trace.V2\312\002\025Google\\Cloud\\Trace\\V2\352\002\030Google::Cloud::Trace::V2", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n5google/cloud/devtools/cloudtrace_v2/proto/trace.proto\x12\x1dgoogle.devtools.cloudtrace.v2\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a\x17google/rpc/status.proto\x1a\x1cgoogle/api/annotations.proto"\xf1\x11\n\x04Span\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x14\n\x07span_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x16\n\x0eparent_span_id\x18\x03 \x01(\t\x12K\n\x0c\x64isplay_name\x18\x04 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableStringB\x03\xe0\x41\x02\x12\x33\n\nstart_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x02\x12\x31\n\x08\x65nd_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x02\x12\x42\n\nattributes\x18\x07 \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.Attributes\x12>\n\x0bstack_trace\x18\x08 \x01(\x0b\x32).google.devtools.cloudtrace.v2.StackTrace\x12\x43\n\x0btime_events\x18\t \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.TimeEvents\x12\x38\n\x05links\x18\n \x01(\x0b\x32).google.devtools.cloudtrace.v2.Span.Links\x12\'\n\x06status\x18\x0b \x01(\x0b\x32\x12.google.rpc.StatusB\x03\xe0\x41\x01\x12\x44\n\x1bsame_process_as_parent_span\x18\x0c \x01(\x0b\x32\x1a.google.protobuf.BoolValueB\x03\xe0\x41\x01\x12:\n\x10\x63hild_span_count\x18\r \x01(\x0b\x32\x1b.google.protobuf.Int32ValueB\x03\xe0\x41\x01\x12\x44\n\tspan_kind\x18\x0e \x01(\x0e\x32,.google.devtools.cloudtrace.v2.Span.SpanKindB\x03\xe0\x41\x01\x1a\xeb\x01\n\nAttributes\x12W\n\rattribute_map\x18\x01 \x03(\x0b\x32@.google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry\x12 \n\x18\x64ropped_attributes_count\x18\x02 \x01(\x05\x1a\x62\n\x11\x41ttributeMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12<\n\x05value\x18\x02 \x01(\x0b\x32-.google.devtools.cloudtrace.v2.AttributeValue:\x02\x38\x01\x1a\xdf\x04\n\tTimeEvent\x12(\n\x04time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12N\n\nannotation\x18\x02 \x01(\x0b\x32\x38.google.devtools.cloudtrace.v2.Span.TimeEvent.AnnotationH\x00\x12S\n\rmessage_event\x18\x03 \x01(\x0b\x32:.google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEventH\x00\x1a\x97\x01\n\nAnnotation\x12\x45\n\x0b\x64\x65scription\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x42\n\nattributes\x18\x02 \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.Attributes\x1a\xdf\x01\n\x0cMessageEvent\x12M\n\x04type\x18\x01 \x01(\x0e\x32?.google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.Type\x12\n\n\x02id\x18\x02 \x01(\x03\x12\x1f\n\x17uncompressed_size_bytes\x18\x03 \x01(\x03\x12\x1d\n\x15\x63ompressed_size_bytes\x18\x04 \x01(\x03"4\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x08\n\x04SENT\x10\x01\x12\x0c\n\x08RECEIVED\x10\x02\x42\x07\n\x05value\x1a\x98\x01\n\nTimeEvents\x12\x41\n\ntime_event\x18\x01 \x03(\x0b\x32-.google.devtools.cloudtrace.v2.Span.TimeEvent\x12!\n\x19\x64ropped_annotations_count\x18\x02 \x01(\x05\x12$\n\x1c\x64ropped_message_events_count\x18\x03 \x01(\x05\x1a\xf7\x01\n\x04Link\x12\x10\n\x08trace_id\x18\x01 \x01(\t\x12\x0f\n\x07span_id\x18\x02 \x01(\t\x12;\n\x04type\x18\x03 \x01(\x0e\x32-.google.devtools.cloudtrace.v2.Span.Link.Type\x12\x42\n\nattributes\x18\x04 \x01(\x0b\x32..google.devtools.cloudtrace.v2.Span.Attributes"K\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11\x43HILD_LINKED_SPAN\x10\x01\x12\x16\n\x12PARENT_LINKED_SPAN\x10\x02\x1a\\\n\x05Links\x12\x36\n\x04link\x18\x01 \x03(\x0b\x32(.google.devtools.cloudtrace.v2.Span.Link\x12\x1b\n\x13\x64ropped_links_count\x18\x02 \x01(\x05"g\n\x08SpanKind\x12\x19\n\x15SPAN_KIND_UNSPECIFIED\x10\x00\x12\x0c\n\x08INTERNAL\x10\x01\x12\n\n\x06SERVER\x10\x02\x12\n\n\x06\x43LIENT\x10\x03\x12\x0c\n\x08PRODUCER\x10\x04\x12\x0c\n\x08\x43ONSUMER\x10\x05:S\xea\x41P\n\x1e\x63loudtrace.googleapis.com/Span\x12.projects/{project}/traces/{trace}/spans/{span}"\x8e\x01\n\x0e\x41ttributeValue\x12H\n\x0cstring_value\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableStringH\x00\x12\x13\n\tint_value\x18\x02 \x01(\x03H\x00\x12\x14\n\nbool_value\x18\x03 \x01(\x08H\x00\x42\x07\n\x05value"\x89\x05\n\nStackTrace\x12K\n\x0cstack_frames\x18\x01 \x01(\x0b\x32\x35.google.devtools.cloudtrace.v2.StackTrace.StackFrames\x12\x1b\n\x13stack_trace_hash_id\x18\x02 \x01(\x03\x1a\x9e\x03\n\nStackFrame\x12G\n\rfunction_name\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12P\n\x16original_function_name\x18\x02 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x43\n\tfile_name\x18\x03 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x13\n\x0bline_number\x18\x04 \x01(\x03\x12\x15\n\rcolumn_number\x18\x05 \x01(\x03\x12:\n\x0bload_module\x18\x06 \x01(\x0b\x32%.google.devtools.cloudtrace.v2.Module\x12H\n\x0esource_version\x18\x07 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x1ap\n\x0bStackFrames\x12\x43\n\x05\x66rame\x18\x01 \x03(\x0b\x32\x34.google.devtools.cloudtrace.v2.StackTrace.StackFrame\x12\x1c\n\x14\x64ropped_frames_count\x18\x02 \x01(\x05"\x8e\x01\n\x06Module\x12@\n\x06module\x18\x01 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString\x12\x42\n\x08\x62uild_id\x18\x02 \x01(\x0b\x32\x30.google.devtools.cloudtrace.v2.TruncatableString"@\n\x11TruncatableString\x12\r\n\x05value\x18\x01 \x01(\t\x12\x1c\n\x14truncated_byte_count\x18\x02 \x01(\x05\x42\xc5\x01\n!com.google.devtools.cloudtrace.v2B\nTraceProtoP\x01ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace\xaa\x02\x15Google.Cloud.Trace.V2\xca\x02\x15Google\\Cloud\\Trace\\V2\xea\x02\x18Google::Cloud::Trace::V2b\x06proto3', - dependencies=[ - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_protobuf_dot_wrappers__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_SPAN_TIMEEVENT_MESSAGEEVENT_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SENT", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RECEIVED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1808, - serialized_end=1860, -) -_sym_db.RegisterEnumDescriptor(_SPAN_TIMEEVENT_MESSAGEEVENT_TYPE) - -_SPAN_LINK_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.devtools.cloudtrace.v2.Span.Link.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHILD_LINKED_SPAN", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PARENT_LINKED_SPAN", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2199, - serialized_end=2274, -) -_sym_db.RegisterEnumDescriptor(_SPAN_LINK_TYPE) - -_SPAN_SPANKIND = _descriptor.EnumDescriptor( - name="SpanKind", - full_name="google.devtools.cloudtrace.v2.Span.SpanKind", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="SPAN_KIND_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INTERNAL", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SERVER", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CLIENT", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PRODUCER", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CONSUMER", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2370, - serialized_end=2473, -) -_sym_db.RegisterEnumDescriptor(_SPAN_SPANKIND) - - -_SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY = _descriptor.Descriptor( - name="AttributeMapEntry", - full_name="google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1161, - serialized_end=1259, -) - -_SPAN_ATTRIBUTES = _descriptor.Descriptor( - name="Attributes", - full_name="google.devtools.cloudtrace.v2.Span.Attributes", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="attribute_map", - full_name="google.devtools.cloudtrace.v2.Span.Attributes.attribute_map", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dropped_attributes_count", - full_name="google.devtools.cloudtrace.v2.Span.Attributes.dropped_attributes_count", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1024, - serialized_end=1259, -) - -_SPAN_TIMEEVENT_ANNOTATION = _descriptor.Descriptor( - name="Annotation", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="description", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation.description", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="attributes", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation.attributes", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1483, - serialized_end=1634, -) - -_SPAN_TIMEEVENT_MESSAGEEVENT = _descriptor.Descriptor( - name="MessageEvent", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="id", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.id", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uncompressed_size_bytes", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.uncompressed_size_bytes", - index=2, - number=3, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compressed_size_bytes", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent.compressed_size_bytes", - index=3, - number=4, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_SPAN_TIMEEVENT_MESSAGEEVENT_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1637, - serialized_end=1860, -) - -_SPAN_TIMEEVENT = _descriptor.Descriptor( - name="TimeEvent", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="time", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="annotation", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.annotation", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="message_event", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.message_event", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_SPAN_TIMEEVENT_ANNOTATION, _SPAN_TIMEEVENT_MESSAGEEVENT,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="value", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvent.value", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1262, - serialized_end=1869, -) - -_SPAN_TIMEEVENTS = _descriptor.Descriptor( - name="TimeEvents", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvents", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="time_event", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvents.time_event", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dropped_annotations_count", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvents.dropped_annotations_count", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dropped_message_events_count", - full_name="google.devtools.cloudtrace.v2.Span.TimeEvents.dropped_message_events_count", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1872, - serialized_end=2024, -) - -_SPAN_LINK = _descriptor.Descriptor( - name="Link", - full_name="google.devtools.cloudtrace.v2.Span.Link", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="trace_id", - full_name="google.devtools.cloudtrace.v2.Span.Link.trace_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="span_id", - full_name="google.devtools.cloudtrace.v2.Span.Link.span_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="type", - full_name="google.devtools.cloudtrace.v2.Span.Link.type", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="attributes", - full_name="google.devtools.cloudtrace.v2.Span.Link.attributes", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_SPAN_LINK_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2027, - serialized_end=2274, -) - -_SPAN_LINKS = _descriptor.Descriptor( - name="Links", - full_name="google.devtools.cloudtrace.v2.Span.Links", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="link", - full_name="google.devtools.cloudtrace.v2.Span.Links.link", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dropped_links_count", - full_name="google.devtools.cloudtrace.v2.Span.Links.dropped_links_count", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2276, - serialized_end=2368, -) - -_SPAN = _descriptor.Descriptor( - name="Span", - full_name="google.devtools.cloudtrace.v2.Span", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.devtools.cloudtrace.v2.Span.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="span_id", - full_name="google.devtools.cloudtrace.v2.Span.span_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_span_id", - full_name="google.devtools.cloudtrace.v2.Span.parent_span_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.devtools.cloudtrace.v2.Span.display_name", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.devtools.cloudtrace.v2.Span.start_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.devtools.cloudtrace.v2.Span.end_time", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="attributes", - full_name="google.devtools.cloudtrace.v2.Span.attributes", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="stack_trace", - full_name="google.devtools.cloudtrace.v2.Span.stack_trace", - index=7, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="time_events", - full_name="google.devtools.cloudtrace.v2.Span.time_events", - index=8, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="links", - full_name="google.devtools.cloudtrace.v2.Span.links", - index=9, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="status", - full_name="google.devtools.cloudtrace.v2.Span.status", - index=10, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="same_process_as_parent_span", - full_name="google.devtools.cloudtrace.v2.Span.same_process_as_parent_span", - index=11, - number=12, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="child_span_count", - full_name="google.devtools.cloudtrace.v2.Span.child_span_count", - index=12, - number=13, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="span_kind", - full_name="google.devtools.cloudtrace.v2.Span.span_kind", - index=13, - number=14, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _SPAN_ATTRIBUTES, - _SPAN_TIMEEVENT, - _SPAN_TIMEEVENTS, - _SPAN_LINK, - _SPAN_LINKS, - ], - enum_types=[_SPAN_SPANKIND,], - serialized_options=b"\352AP\n\036cloudtrace.googleapis.com/Span\022.projects/{project}/traces/{trace}/spans/{span}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=269, - serialized_end=2558, -) - - -_ATTRIBUTEVALUE = _descriptor.Descriptor( - name="AttributeValue", - full_name="google.devtools.cloudtrace.v2.AttributeValue", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="string_value", - full_name="google.devtools.cloudtrace.v2.AttributeValue.string_value", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="int_value", - full_name="google.devtools.cloudtrace.v2.AttributeValue.int_value", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bool_value", - full_name="google.devtools.cloudtrace.v2.AttributeValue.bool_value", - index=2, - number=3, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="value", - full_name="google.devtools.cloudtrace.v2.AttributeValue.value", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=2561, - serialized_end=2703, -) - - -_STACKTRACE_STACKFRAME = _descriptor.Descriptor( - name="StackFrame", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="function_name", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.function_name", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="original_function_name", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.original_function_name", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="file_name", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.file_name", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="line_number", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.line_number", - index=3, - number=4, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="column_number", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.column_number", - index=4, - number=5, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="load_module", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.load_module", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_version", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrame.source_version", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2827, - serialized_end=3241, -) - -_STACKTRACE_STACKFRAMES = _descriptor.Descriptor( - name="StackFrames", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrames", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="frame", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrames.frame", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="dropped_frames_count", - full_name="google.devtools.cloudtrace.v2.StackTrace.StackFrames.dropped_frames_count", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3243, - serialized_end=3355, -) - -_STACKTRACE = _descriptor.Descriptor( - name="StackTrace", - full_name="google.devtools.cloudtrace.v2.StackTrace", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="stack_frames", - full_name="google.devtools.cloudtrace.v2.StackTrace.stack_frames", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="stack_trace_hash_id", - full_name="google.devtools.cloudtrace.v2.StackTrace.stack_trace_hash_id", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_STACKTRACE_STACKFRAME, _STACKTRACE_STACKFRAMES,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2706, - serialized_end=3355, -) - - -_MODULE = _descriptor.Descriptor( - name="Module", - full_name="google.devtools.cloudtrace.v2.Module", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="module", - full_name="google.devtools.cloudtrace.v2.Module.module", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="build_id", - full_name="google.devtools.cloudtrace.v2.Module.build_id", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3358, - serialized_end=3500, -) - - -_TRUNCATABLESTRING = _descriptor.Descriptor( - name="TruncatableString", - full_name="google.devtools.cloudtrace.v2.TruncatableString", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="value", - full_name="google.devtools.cloudtrace.v2.TruncatableString.value", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="truncated_byte_count", - full_name="google.devtools.cloudtrace.v2.TruncatableString.truncated_byte_count", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3502, - serialized_end=3566, -) - -_SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY.fields_by_name[ - "value" -].message_type = _ATTRIBUTEVALUE -_SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY.containing_type = _SPAN_ATTRIBUTES -_SPAN_ATTRIBUTES.fields_by_name[ - "attribute_map" -].message_type = _SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY -_SPAN_ATTRIBUTES.containing_type = _SPAN -_SPAN_TIMEEVENT_ANNOTATION.fields_by_name[ - "description" -].message_type = _TRUNCATABLESTRING -_SPAN_TIMEEVENT_ANNOTATION.fields_by_name["attributes"].message_type = _SPAN_ATTRIBUTES -_SPAN_TIMEEVENT_ANNOTATION.containing_type = _SPAN_TIMEEVENT -_SPAN_TIMEEVENT_MESSAGEEVENT.fields_by_name[ - "type" -].enum_type = _SPAN_TIMEEVENT_MESSAGEEVENT_TYPE -_SPAN_TIMEEVENT_MESSAGEEVENT.containing_type = _SPAN_TIMEEVENT -_SPAN_TIMEEVENT_MESSAGEEVENT_TYPE.containing_type = _SPAN_TIMEEVENT_MESSAGEEVENT -_SPAN_TIMEEVENT.fields_by_name[ - "time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SPAN_TIMEEVENT.fields_by_name["annotation"].message_type = _SPAN_TIMEEVENT_ANNOTATION -_SPAN_TIMEEVENT.fields_by_name[ - "message_event" -].message_type = _SPAN_TIMEEVENT_MESSAGEEVENT -_SPAN_TIMEEVENT.containing_type = _SPAN -_SPAN_TIMEEVENT.oneofs_by_name["value"].fields.append( - _SPAN_TIMEEVENT.fields_by_name["annotation"] -) -_SPAN_TIMEEVENT.fields_by_name[ - "annotation" -].containing_oneof = _SPAN_TIMEEVENT.oneofs_by_name["value"] -_SPAN_TIMEEVENT.oneofs_by_name["value"].fields.append( - _SPAN_TIMEEVENT.fields_by_name["message_event"] -) -_SPAN_TIMEEVENT.fields_by_name[ - "message_event" -].containing_oneof = _SPAN_TIMEEVENT.oneofs_by_name["value"] -_SPAN_TIMEEVENTS.fields_by_name["time_event"].message_type = _SPAN_TIMEEVENT -_SPAN_TIMEEVENTS.containing_type = _SPAN -_SPAN_LINK.fields_by_name["type"].enum_type = _SPAN_LINK_TYPE -_SPAN_LINK.fields_by_name["attributes"].message_type = _SPAN_ATTRIBUTES -_SPAN_LINK.containing_type = _SPAN -_SPAN_LINK_TYPE.containing_type = _SPAN_LINK -_SPAN_LINKS.fields_by_name["link"].message_type = _SPAN_LINK -_SPAN_LINKS.containing_type = _SPAN -_SPAN.fields_by_name["display_name"].message_type = _TRUNCATABLESTRING -_SPAN.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SPAN.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SPAN.fields_by_name["attributes"].message_type = _SPAN_ATTRIBUTES -_SPAN.fields_by_name["stack_trace"].message_type = _STACKTRACE -_SPAN.fields_by_name["time_events"].message_type = _SPAN_TIMEEVENTS -_SPAN.fields_by_name["links"].message_type = _SPAN_LINKS -_SPAN.fields_by_name["status"].message_type = google_dot_rpc_dot_status__pb2._STATUS -_SPAN.fields_by_name[ - "same_process_as_parent_span" -].message_type = google_dot_protobuf_dot_wrappers__pb2._BOOLVALUE -_SPAN.fields_by_name[ - "child_span_count" -].message_type = google_dot_protobuf_dot_wrappers__pb2._INT32VALUE -_SPAN.fields_by_name["span_kind"].enum_type = _SPAN_SPANKIND -_SPAN_SPANKIND.containing_type = _SPAN -_ATTRIBUTEVALUE.fields_by_name["string_value"].message_type = _TRUNCATABLESTRING -_ATTRIBUTEVALUE.oneofs_by_name["value"].fields.append( - _ATTRIBUTEVALUE.fields_by_name["string_value"] -) -_ATTRIBUTEVALUE.fields_by_name[ - "string_value" -].containing_oneof = _ATTRIBUTEVALUE.oneofs_by_name["value"] -_ATTRIBUTEVALUE.oneofs_by_name["value"].fields.append( - _ATTRIBUTEVALUE.fields_by_name["int_value"] -) -_ATTRIBUTEVALUE.fields_by_name[ - "int_value" -].containing_oneof = _ATTRIBUTEVALUE.oneofs_by_name["value"] -_ATTRIBUTEVALUE.oneofs_by_name["value"].fields.append( - _ATTRIBUTEVALUE.fields_by_name["bool_value"] -) -_ATTRIBUTEVALUE.fields_by_name[ - "bool_value" -].containing_oneof = _ATTRIBUTEVALUE.oneofs_by_name["value"] -_STACKTRACE_STACKFRAME.fields_by_name["function_name"].message_type = _TRUNCATABLESTRING -_STACKTRACE_STACKFRAME.fields_by_name[ - "original_function_name" -].message_type = _TRUNCATABLESTRING -_STACKTRACE_STACKFRAME.fields_by_name["file_name"].message_type = _TRUNCATABLESTRING -_STACKTRACE_STACKFRAME.fields_by_name["load_module"].message_type = _MODULE -_STACKTRACE_STACKFRAME.fields_by_name[ - "source_version" -].message_type = _TRUNCATABLESTRING -_STACKTRACE_STACKFRAME.containing_type = _STACKTRACE -_STACKTRACE_STACKFRAMES.fields_by_name["frame"].message_type = _STACKTRACE_STACKFRAME -_STACKTRACE_STACKFRAMES.containing_type = _STACKTRACE -_STACKTRACE.fields_by_name["stack_frames"].message_type = _STACKTRACE_STACKFRAMES -_MODULE.fields_by_name["module"].message_type = _TRUNCATABLESTRING -_MODULE.fields_by_name["build_id"].message_type = _TRUNCATABLESTRING -DESCRIPTOR.message_types_by_name["Span"] = _SPAN -DESCRIPTOR.message_types_by_name["AttributeValue"] = _ATTRIBUTEVALUE -DESCRIPTOR.message_types_by_name["StackTrace"] = _STACKTRACE -DESCRIPTOR.message_types_by_name["Module"] = _MODULE -DESCRIPTOR.message_types_by_name["TruncatableString"] = _TRUNCATABLESTRING -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Span = _reflection.GeneratedProtocolMessageType( - "Span", - (_message.Message,), - { - "Attributes": _reflection.GeneratedProtocolMessageType( - "Attributes", - (_message.Message,), - { - "AttributeMapEntry": _reflection.GeneratedProtocolMessageType( - "AttributeMapEntry", - (_message.Message,), - { - "DESCRIPTOR": _SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2" - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Attributes.AttributeMapEntry) - }, - ), - "DESCRIPTOR": _SPAN_ATTRIBUTES, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A set of attributes, each in the format ``[KEY]:[VALUE]``. - - Attributes: - attribute_map: - The set of attributes. Each attribute’s key can be up to 128 - bytes long. The value can be a string up to 256 bytes, a - signed 64-bit integer, or the Boolean values ``true`` and - ``false``. For example: :: "/instance_id": { - "string_value": { "value": "my-instance" } } - "/http/request_bytes": { "int_value": 300 } - "abc.com/myattribute": { "bool_value": false } - dropped_attributes_count: - The number of attributes that were discarded. Attributes can - be discarded because their keys are too long or because there - are too many attributes. If this value is 0 then all - attributes are valid. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Attributes) - }, - ), - "TimeEvent": _reflection.GeneratedProtocolMessageType( - "TimeEvent", - (_message.Message,), - { - "Annotation": _reflection.GeneratedProtocolMessageType( - "Annotation", - (_message.Message,), - { - "DESCRIPTOR": _SPAN_TIMEEVENT_ANNOTATION, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """Text annotation with a set of attributes. - - Attributes: - description: - A user-supplied message describing the event. The maximum - length for the description is 256 bytes. - attributes: - A set of attributes on the annotation. You can have up to 4 - attributes per Annotation. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvent.Annotation) - }, - ), - "MessageEvent": _reflection.GeneratedProtocolMessageType( - "MessageEvent", - (_message.Message,), - { - "DESCRIPTOR": _SPAN_TIMEEVENT_MESSAGEEVENT, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """An event describing a message sent/received between Spans. - - Attributes: - type: - Type of MessageEvent. Indicates whether the message was sent - or received. - id: - An identifier for the MessageEvent’s message that can be used - to match SENT and RECEIVED MessageEvents. It is recommended to - be unique within a Span. - uncompressed_size_bytes: - The number of uncompressed bytes sent or received. - compressed_size_bytes: - The number of compressed bytes sent or received. If missing - assumed to be the same size as uncompressed. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent) - }, - ), - "DESCRIPTOR": _SPAN_TIMEEVENT, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A time-stamped annotation or message event in the Span. - - Attributes: - time: - The timestamp indicating the time the event occurred. - value: - A ``TimeEvent`` can contain either an ``Annotation`` object or - a ``MessageEvent`` object, but not both. - annotation: - Text annotation with a set of attributes. - message_event: - An event describing a message sent/received between Spans. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvent) - }, - ), - "TimeEvents": _reflection.GeneratedProtocolMessageType( - "TimeEvents", - (_message.Message,), - { - "DESCRIPTOR": _SPAN_TIMEEVENTS, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A collection of ``TimeEvent``\ s. A ``TimeEvent`` is a time-stamped - annotation on the span, consisting of either user-supplied key:value - pairs, or details of a message sent/received between Spans. - - Attributes: - time_event: - A collection of ``TimeEvent``\ s. - dropped_annotations_count: - The number of dropped annotations in all the included time - events. If the value is 0, then no annotations were dropped. - dropped_message_events_count: - The number of dropped message events in all the included time - events. If the value is 0, then no message events were - dropped. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.TimeEvents) - }, - ), - "Link": _reflection.GeneratedProtocolMessageType( - "Link", - (_message.Message,), - { - "DESCRIPTOR": _SPAN_LINK, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A pointer from the current span to another span in the same trace or - in a different trace. For example, this can be used in batching - operations, where a single batch handler processes multiple requests - from different traces or when the handler receives a request from a - different project. - - Attributes: - trace_id: - The [TRACE_ID] for a trace within a project. - span_id: - The [SPAN_ID] for a span within a trace. - type: - The relationship of the current span relative to the linked - span. - attributes: - A set of attributes on the link. You have have up to 32 - attributes per link. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Link) - }, - ), - "Links": _reflection.GeneratedProtocolMessageType( - "Links", - (_message.Message,), - { - "DESCRIPTOR": _SPAN_LINKS, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A collection of links, which are references from this span to a span - in the same or different trace. - - Attributes: - link: - A collection of links. - dropped_links_count: - The number of dropped links after the maximum size was - enforced. If this value is 0, then no links were dropped. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span.Links) - }, - ), - "DESCRIPTOR": _SPAN, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A span represents a single operation within a trace. Spans can be - nested to form a trace tree. Often, a trace contains a root span that - describes the end-to-end latency, and one or more subspans for its - sub-operations. A trace can also contain multiple root spans, or none - at all. Spans do not need to be contiguous—there may be gaps or - overlaps between spans in a trace. - - Attributes: - name: - Required. The resource name of the span in the following - format: :: - projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] - [TRACE_ID] is a unique identifier for a trace within a - project; it is a 32-character hexadecimal encoding of a - 16-byte array. [SPAN_ID] is a unique identifier for a span - within a trace; it is a 16-character hexadecimal encoding of - an 8-byte array. - span_id: - Required. The [SPAN_ID] portion of the span’s resource name. - parent_span_id: - The [SPAN_ID] of this span’s parent span. If this is a root - span, then this field must be empty. - display_name: - Required. A description of the span’s operation (up to 128 - bytes). Stackdriver Trace displays the description in the - Google Cloud Platform Console. For example, the display name - can be a qualified method name or a file name and a line - number where the operation is called. A best practice is to - use the same display name within an application and at the - same call point. This makes it easier to correlate spans in - different traces. - start_time: - Required. The start time of the span. On the client side, this - is the time kept by the local machine where the span execution - starts. On the server side, this is the time when the server’s - application handler starts running. - end_time: - Required. The end time of the span. On the client side, this - is the time kept by the local machine where the span execution - ends. On the server side, this is the time when the server - application handler stops running. - attributes: - A set of attributes on the span. You can have up to 32 - attributes per span. - stack_trace: - Stack trace captured at the start of the span. - time_events: - A set of time events. You can have up to 32 annotations and - 128 message events per span. - links: - Links associated with the span. You can have up to 128 links - per Span. - status: - Optional. The final status for this span. - same_process_as_parent_span: - Optional. Set this parameter to indicate whether this span is - in the same process as its parent. If you do not set this - parameter, Stackdriver Trace is unable to take advantage of - this helpful information. - child_span_count: - Optional. The number of child spans that were generated while - this span was active. If set, allows implementation to detect - missing child spans. - span_kind: - Optional. Distinguishes between spans generated in a - particular context. For example, two spans with the same name - may be distinguished using ``CLIENT`` (caller) and ``SERVER`` - (callee) to identify an RPC call. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Span) - }, -) -_sym_db.RegisterMessage(Span) -_sym_db.RegisterMessage(Span.Attributes) -_sym_db.RegisterMessage(Span.Attributes.AttributeMapEntry) -_sym_db.RegisterMessage(Span.TimeEvent) -_sym_db.RegisterMessage(Span.TimeEvent.Annotation) -_sym_db.RegisterMessage(Span.TimeEvent.MessageEvent) -_sym_db.RegisterMessage(Span.TimeEvents) -_sym_db.RegisterMessage(Span.Link) -_sym_db.RegisterMessage(Span.Links) - -AttributeValue = _reflection.GeneratedProtocolMessageType( - "AttributeValue", - (_message.Message,), - { - "DESCRIPTOR": _ATTRIBUTEVALUE, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """The allowed types for [VALUE] in a ``[KEY]:[VALUE]`` attribute. - - Attributes: - value: - The type of the value. - string_value: - A string up to 256 bytes long. - int_value: - A 64-bit signed integer. - bool_value: - A Boolean value represented by ``true`` or ``false``. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.AttributeValue) - }, -) -_sym_db.RegisterMessage(AttributeValue) - -StackTrace = _reflection.GeneratedProtocolMessageType( - "StackTrace", - (_message.Message,), - { - "StackFrame": _reflection.GeneratedProtocolMessageType( - "StackFrame", - (_message.Message,), - { - "DESCRIPTOR": _STACKTRACE_STACKFRAME, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """Represents a single stack frame in a stack trace. - - Attributes: - function_name: - The fully-qualified name that uniquely identifies the function - or method that is active in this frame (up to 1024 bytes). - original_function_name: - An un-mangled function name, if ``function_name`` is `mangled - `__. The name - can be fully-qualified (up to 1024 bytes). - file_name: - The name of the source file where the function call appears - (up to 256 bytes). - line_number: - The line number in ``file_name`` where the function call - appears. - column_number: - The column number where the function call appears, if - available. This is important in JavaScript because of its - anonymous functions. - load_module: - The binary module from where the code was loaded. - source_version: - The version of the deployed source code (up to 128 bytes). - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.StackTrace.StackFrame) - }, - ), - "StackFrames": _reflection.GeneratedProtocolMessageType( - "StackFrames", - (_message.Message,), - { - "DESCRIPTOR": _STACKTRACE_STACKFRAMES, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A collection of stack frames, which can be truncated. - - Attributes: - frame: - Stack frames in this call stack. - dropped_frames_count: - The number of stack frames that were dropped because there - were too many stack frames. If this value is 0, then no stack - frames were dropped. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.StackTrace.StackFrames) - }, - ), - "DESCRIPTOR": _STACKTRACE, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """A call stack appearing in a trace. - - Attributes: - stack_frames: - Stack frames in this stack trace. A maximum of 128 frames are - allowed. - stack_trace_hash_id: - The hash ID is used to conserve network bandwidth for - duplicate stack traces within a single trace. Often multiple - spans will have identical stack traces. The first occurrence - of a stack trace should contain both the ``stackFrame`` - content and a value in ``stackTraceHashId``. Subsequent spans - within the same request can refer to that stack trace by only - setting ``stackTraceHashId``. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.StackTrace) - }, -) -_sym_db.RegisterMessage(StackTrace) -_sym_db.RegisterMessage(StackTrace.StackFrame) -_sym_db.RegisterMessage(StackTrace.StackFrames) - -Module = _reflection.GeneratedProtocolMessageType( - "Module", - (_message.Message,), - { - "DESCRIPTOR": _MODULE, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """Binary module. - - Attributes: - module: - For example: main binary, kernel modules, and dynamic - libraries such as libc.so, sharedlib.so (up to 256 bytes). - build_id: - A unique identifier for the module, usually a hash of its - contents (up to 128 bytes). - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.Module) - }, -) -_sym_db.RegisterMessage(Module) - -TruncatableString = _reflection.GeneratedProtocolMessageType( - "TruncatableString", - (_message.Message,), - { - "DESCRIPTOR": _TRUNCATABLESTRING, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.trace_pb2", - "__doc__": """Represents a string that might be shortened to a specified length. - - Attributes: - value: - The shortened string. For example, if the original string is - 500 bytes long and the limit of the string is 128 bytes, then - ``value`` contains the first 128 bytes of the 500-byte string. - Truncation always happens on a UTF8 character boundary. If - there are multi-byte characters in the string, then the length - of the shortened string might be less than the size limit. - truncated_byte_count: - The number of bytes removed from the original string. If this - value is 0, then the string was not shortened. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.TruncatableString) - }, -) -_sym_db.RegisterMessage(TruncatableString) - - -DESCRIPTOR._options = None -_SPAN_ATTRIBUTES_ATTRIBUTEMAPENTRY._options = None -_SPAN.fields_by_name["name"]._options = None -_SPAN.fields_by_name["span_id"]._options = None -_SPAN.fields_by_name["display_name"]._options = None -_SPAN.fields_by_name["start_time"]._options = None -_SPAN.fields_by_name["end_time"]._options = None -_SPAN.fields_by_name["status"]._options = None -_SPAN.fields_by_name["same_process_as_parent_span"]._options = None -_SPAN.fields_by_name["child_span_count"]._options = None -_SPAN.fields_by_name["span_kind"]._options = None -_SPAN._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/trace_v2/proto/trace_pb2_grpc.py b/google/cloud/trace_v2/proto/trace_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/trace_v2/proto/trace_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/trace_v2/proto/tracing.proto b/google/cloud/trace_v2/proto/tracing.proto deleted file mode 100644 index a25a0dd7..00000000 --- a/google/cloud/trace_v2/proto/tracing.proto +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.devtools.cloudtrace.v2; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/devtools/cloudtrace/v2/trace.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/timestamp.proto"; - -option csharp_namespace = "Google.Cloud.Trace.V2"; -option go_package = "google.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace"; -option java_multiple_files = true; -option java_outer_classname = "TracingProto"; -option java_package = "com.google.devtools.cloudtrace.v2"; -option php_namespace = "Google\\Cloud\\Trace\\V2"; -option ruby_package = "Google::Cloud::Trace::V2"; - -// This file describes an API for collecting and viewing traces and spans -// within a trace. A Trace is a collection of spans corresponding to a single -// operation or set of operations for an application. A span is an individual -// timed event which forms a node of the trace tree. A single trace may -// contain span(s) from multiple services. -service TraceService { - option (google.api.default_host) = "cloudtrace.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/trace.append"; - - // Sends new spans to new or existing traces. You cannot update - // existing spans. - rpc BatchWriteSpans(BatchWriteSpansRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v2/{name=projects/*}/traces:batchWrite" - body: "*" - }; - option (google.api.method_signature) = "name,spans"; - } - - // Creates a new span. - rpc CreateSpan(Span) returns (Span) { - option (google.api.http) = { - post: "/v2/{name=projects/*/traces/*/spans/*}" - body: "*" - }; - } -} - -// The request message for the `BatchWriteSpans` method. -message BatchWriteSpansRequest { - // Required. The name of the project where the spans belong. The format is - // `projects/[PROJECT_ID]`. - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "cloudresourcemanager.googleapis.com/Project" - } - ]; - - // Required. A list of new spans. The span names must not match existing - // spans, or the results are undefined. - repeated Span spans = 2 [(google.api.field_behavior) = REQUIRED]; -} diff --git a/google/cloud/trace_v2/proto/tracing_pb2.py b/google/cloud/trace_v2/proto/tracing_pb2.py deleted file mode 100644 index d853764a..00000000 --- a/google/cloud/trace_v2/proto/tracing_pb2.py +++ /dev/null @@ -1,174 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/devtools/cloudtrace_v2/proto/tracing.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.trace_v2.proto import ( - trace_pb2 as google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/devtools/cloudtrace_v2/proto/tracing.proto", - package="google.devtools.cloudtrace.v2", - syntax="proto3", - serialized_options=b"\n!com.google.devtools.cloudtrace.v2B\014TracingProtoP\001ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace\252\002\025Google.Cloud.Trace.V2\312\002\025Google\\Cloud\\Trace\\V2\352\002\030Google::Cloud::Trace::V2", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/devtools/cloudtrace_v2/proto/tracing.proto\x12\x1dgoogle.devtools.cloudtrace.v2\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x35google/cloud/devtools/cloudtrace_v2/proto/trace.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x94\x01\n\x16\x42\x61tchWriteSpansRequest\x12\x41\n\x04name\x18\x01 \x01(\tB3\xe0\x41\x02\xfa\x41-\n+cloudresourcemanager.googleapis.com/Project\x12\x37\n\x05spans\x18\x02 \x03(\x0b\x32#.google.devtools.cloudtrace.v2.SpanB\x03\xe0\x41\x02\x32\xba\x03\n\x0cTraceService\x12\xa1\x01\n\x0f\x42\x61tchWriteSpans\x12\x35.google.devtools.cloudtrace.v2.BatchWriteSpansRequest\x1a\x16.google.protobuf.Empty"?\x82\xd3\xe4\x93\x02,"\'/v2/{name=projects/*}/traces:batchWrite:\x01*\xda\x41\nname,spans\x12\x89\x01\n\nCreateSpan\x12#.google.devtools.cloudtrace.v2.Span\x1a#.google.devtools.cloudtrace.v2.Span"1\x82\xd3\xe4\x93\x02+"&/v2/{name=projects/*/traces/*/spans/*}:\x01*\x1az\xca\x41\x19\x63loudtrace.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/trace.appendB\xc7\x01\n!com.google.devtools.cloudtrace.v2B\x0cTracingProtoP\x01ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v2;cloudtrace\xaa\x02\x15Google.Cloud.Trace.V2\xca\x02\x15Google\\Cloud\\Trace\\V2\xea\x02\x18Google::Cloud::Trace::V2b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_BATCHWRITESPANSREQUEST = _descriptor.Descriptor( - name="BatchWriteSpansRequest", - full_name="google.devtools.cloudtrace.v2.BatchWriteSpansRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.devtools.cloudtrace.v2.BatchWriteSpansRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A-\n+cloudresourcemanager.googleapis.com/Project", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="spans", - full_name="google.devtools.cloudtrace.v2.BatchWriteSpansRequest.spans", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=323, - serialized_end=471, -) - -_BATCHWRITESPANSREQUEST.fields_by_name[ - "spans" -].message_type = ( - google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2._SPAN -) -DESCRIPTOR.message_types_by_name["BatchWriteSpansRequest"] = _BATCHWRITESPANSREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -BatchWriteSpansRequest = _reflection.GeneratedProtocolMessageType( - "BatchWriteSpansRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHWRITESPANSREQUEST, - "__module__": "google.cloud.devtools.cloudtrace_v2.proto.tracing_pb2", - "__doc__": """The request message for the ``BatchWriteSpans`` method. - - Attributes: - name: - Required. The name of the project where the spans belong. The - format is ``projects/[PROJECT_ID]``. - spans: - Required. A list of new spans. The span names must not match - existing spans, or the results are undefined. - """, - # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v2.BatchWriteSpansRequest) - }, -) -_sym_db.RegisterMessage(BatchWriteSpansRequest) - - -DESCRIPTOR._options = None -_BATCHWRITESPANSREQUEST.fields_by_name["name"]._options = None -_BATCHWRITESPANSREQUEST.fields_by_name["spans"]._options = None - -_TRACESERVICE = _descriptor.ServiceDescriptor( - name="TraceService", - full_name="google.devtools.cloudtrace.v2.TraceService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudtrace.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/trace.append", - create_key=_descriptor._internal_create_key, - serialized_start=474, - serialized_end=916, - methods=[ - _descriptor.MethodDescriptor( - name="BatchWriteSpans", - full_name="google.devtools.cloudtrace.v2.TraceService.BatchWriteSpans", - index=0, - containing_service=None, - input_type=_BATCHWRITESPANSREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002,\"'/v2/{name=projects/*}/traces:batchWrite:\001*\332A\nname,spans", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateSpan", - full_name="google.devtools.cloudtrace.v2.TraceService.CreateSpan", - index=1, - containing_service=None, - input_type=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2._SPAN, - output_type=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2._SPAN, - serialized_options=b'\202\323\344\223\002+"&/v2/{name=projects/*/traces/*/spans/*}:\001*', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_TRACESERVICE) - -DESCRIPTOR.services_by_name["TraceService"] = _TRACESERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/trace_v2/proto/tracing_pb2_grpc.py b/google/cloud/trace_v2/proto/tracing_pb2_grpc.py deleted file mode 100644 index b4c0d910..00000000 --- a/google/cloud/trace_v2/proto/tracing_pb2_grpc.py +++ /dev/null @@ -1,144 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.trace_v2.proto import ( - trace_pb2 as google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2, -) -from google.cloud.trace_v2.proto import ( - tracing_pb2 as google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_tracing__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class TraceServiceStub(object): - """This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. A single trace may - contain span(s) from multiple services. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.BatchWriteSpans = channel.unary_unary( - "/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans", - request_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_tracing__pb2.BatchWriteSpansRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.CreateSpan = channel.unary_unary( - "/google.devtools.cloudtrace.v2.TraceService/CreateSpan", - request_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.SerializeToString, - response_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.FromString, - ) - - -class TraceServiceServicer(object): - """This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. A single trace may - contain span(s) from multiple services. - """ - - def BatchWriteSpans(self, request, context): - """Sends new spans to new or existing traces. You cannot update - existing spans. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateSpan(self, request, context): - """Creates a new span. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_TraceServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "BatchWriteSpans": grpc.unary_unary_rpc_method_handler( - servicer.BatchWriteSpans, - request_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_tracing__pb2.BatchWriteSpansRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "CreateSpan": grpc.unary_unary_rpc_method_handler( - servicer.CreateSpan, - request_deserializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.FromString, - response_serializer=google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.devtools.cloudtrace.v2.TraceService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class TraceService(object): - """This file describes an API for collecting and viewing traces and spans - within a trace. A Trace is a collection of spans corresponding to a single - operation or set of operations for an application. A span is an individual - timed event which forms a node of the trace tree. A single trace may - contain span(s) from multiple services. - """ - - @staticmethod - def BatchWriteSpans( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans", - google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_tracing__pb2.BatchWriteSpansRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateSpan( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.devtools.cloudtrace.v2.TraceService/CreateSpan", - google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.SerializeToString, - google_dot_cloud_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/trace_v2/py.typed b/google/cloud/trace_v2/py.typed new file mode 100644 index 00000000..4717a6c0 --- /dev/null +++ b/google/cloud/trace_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-trace package uses inline types. diff --git a/google/cloud/trace/v1/__init__.py b/google/cloud/trace_v2/services/__init__.py similarity index 80% rename from google/cloud/trace/v1/__init__.py rename to google/cloud/trace_v2/services/__init__.py index 4c6bd18d..42ffdf2b 100644 --- a/google/cloud/trace/v1/__init__.py +++ b/google/cloud/trace_v2/services/__init__.py @@ -1,4 +1,6 @@ -# Copyright 2017 Google LLC +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,11 +13,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -from google.cloud.trace.v1.client import Client - - -__all__ = ["Client", "SCOPE"] - - -SCOPE = Client.SCOPE +# diff --git a/google/cloud/trace_v2/services/trace_service/__init__.py b/google/cloud/trace_v2/services/trace_service/__init__.py new file mode 100644 index 00000000..e06e796c --- /dev/null +++ b/google/cloud/trace_v2/services/trace_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import TraceServiceClient +from .async_client import TraceServiceAsyncClient + +__all__ = ( + "TraceServiceClient", + "TraceServiceAsyncClient", +) diff --git a/google/cloud/trace_v2/services/trace_service/async_client.py b/google/cloud/trace_v2/services/trace_service/async_client.py new file mode 100644 index 00000000..a400f60a --- /dev/null +++ b/google/cloud/trace_v2/services/trace_service/async_client.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v2.types import trace +from google.cloud.trace_v2.types import tracing +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import wrappers_pb2 as wrappers # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import TraceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport +from .client import TraceServiceClient + + +class TraceServiceAsyncClient: + """This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. A single trace may contain span(s) from + multiple services. + """ + + _client: TraceServiceClient + + DEFAULT_ENDPOINT = TraceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TraceServiceClient.DEFAULT_MTLS_ENDPOINT + + span_path = staticmethod(TraceServiceClient.span_path) + + from_service_account_file = TraceServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(TraceServiceClient).get_transport_class, type(TraceServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TraceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the trace service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TraceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = TraceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def batch_write_spans( + self, + request: tracing.BatchWriteSpansRequest = None, + *, + name: str = None, + spans: Sequence[trace.Span] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Sends new spans to new or existing traces. You cannot + update existing spans. + + Args: + request (:class:`~.tracing.BatchWriteSpansRequest`): + The request object. The request message for the + `BatchWriteSpans` method. + name (:class:`str`): + Required. The name of the project where the spans + belong. The format is ``projects/[PROJECT_ID]``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + spans (:class:`Sequence[~.trace.Span]`): + Required. A list of new spans. The + span names must not match existing + spans, or the results are undefined. + This corresponds to the ``spans`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, spans]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = tracing.BatchWriteSpansRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if spans is not None: + request.spans = spans + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_write_spans, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_span( + self, + request: trace.Span = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trace.Span: + r"""Creates a new span. + + Args: + request (:class:`~.trace.Span`): + The request object. A span represents a single operation + within a trace. Spans can be nested to form a trace + tree. Often, a trace contains a root span that describes + the end-to-end latency, and one or more subspans for its + sub-operations. A trace can also contain multiple root + spans, or none at all. Spans do not need to be + contiguous—there may be gaps or overlaps between + spans in a trace. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.trace.Span: + A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. A trace + can also contain multiple root spans, or + none at all. Spans do not need to be + contiguous—there may be gaps or + overlaps between spans in a trace. + + """ + # Create or coerce a protobuf request object. + + request = trace.Span(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_span, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-trace",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TraceServiceAsyncClient",) diff --git a/google/cloud/trace_v2/services/trace_service/client.py b/google/cloud/trace_v2/services/trace_service/client.py new file mode 100644 index 00000000..816ad9d3 --- /dev/null +++ b/google/cloud/trace_v2/services/trace_service/client.py @@ -0,0 +1,403 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.trace_v2.types import trace +from google.cloud.trace_v2.types import tracing +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import wrappers_pb2 as wrappers # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import TraceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TraceServiceGrpcTransport +from .transports.grpc_asyncio import TraceServiceGrpcAsyncIOTransport + + +class TraceServiceClientMeta(type): + """Metaclass for the TraceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] + _transport_registry["grpc"] = TraceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[TraceServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TraceServiceClient(metaclass=TraceServiceClientMeta): + """This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. A single trace may contain span(s) from + multiple services. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudtrace.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def span_path(project: str, trace: str, span: str,) -> str: + """Return a fully-qualified span string.""" + return "projects/{project}/traces/{trace}/spans/{span}".format( + project=project, trace=trace, span=span, + ) + + @staticmethod + def parse_span_path(path: str) -> Dict[str, str]: + """Parse a span path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/traces/(?P.+?)/spans/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, TraceServiceTransport] = None, + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the trace service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TraceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TraceServiceTransport): + # transport is a TraceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def batch_write_spans( + self, + request: tracing.BatchWriteSpansRequest = None, + *, + name: str = None, + spans: Sequence[trace.Span] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Sends new spans to new or existing traces. You cannot + update existing spans. + + Args: + request (:class:`~.tracing.BatchWriteSpansRequest`): + The request object. The request message for the + `BatchWriteSpans` method. + name (:class:`str`): + Required. The name of the project where the spans + belong. The format is ``projects/[PROJECT_ID]``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + spans (:class:`Sequence[~.trace.Span]`): + Required. A list of new spans. The + span names must not match existing + spans, or the results are undefined. + This corresponds to the ``spans`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, spans]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a tracing.BatchWriteSpansRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tracing.BatchWriteSpansRequest): + request = tracing.BatchWriteSpansRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if spans is not None: + request.spans = spans + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_write_spans] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_span( + self, + request: trace.Span = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trace.Span: + r"""Creates a new span. + + Args: + request (:class:`~.trace.Span`): + The request object. A span represents a single operation + within a trace. Spans can be nested to form a trace + tree. Often, a trace contains a root span that describes + the end-to-end latency, and one or more subspans for its + sub-operations. A trace can also contain multiple root + spans, or none at all. Spans do not need to be + contiguous—there may be gaps or overlaps between + spans in a trace. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.trace.Span: + A span represents a single operation + within a trace. Spans can be nested to + form a trace tree. Often, a trace + contains a root span that describes the + end-to-end latency, and one or more + subspans for its sub-operations. A trace + can also contain multiple root spans, or + none at all. Spans do not need to be + contiguous—there may be gaps or + overlaps between spans in a trace. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a trace.Span. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, trace.Span): + request = trace.Span(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_span] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-trace",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("TraceServiceClient",) diff --git a/google/cloud/trace_v2/services/trace_service/transports/__init__.py b/google/cloud/trace_v2/services/trace_service/transports/__init__.py new file mode 100644 index 00000000..134fa0ad --- /dev/null +++ b/google/cloud/trace_v2/services/trace_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import TraceServiceTransport +from .grpc import TraceServiceGrpcTransport +from .grpc_asyncio import TraceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TraceServiceTransport]] +_transport_registry["grpc"] = TraceServiceGrpcTransport +_transport_registry["grpc_asyncio"] = TraceServiceGrpcAsyncIOTransport + + +__all__ = ( + "TraceServiceTransport", + "TraceServiceGrpcTransport", + "TraceServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/trace_v2/services/trace_service/transports/base.py b/google/cloud/trace_v2/services/trace_service/transports/base.py new file mode 100644 index 00000000..a271eea7 --- /dev/null +++ b/google/cloud/trace_v2/services/trace_service/transports/base.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.trace_v2.types import trace +from google.cloud.trace_v2.types import tracing +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-trace",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class TraceServiceTransport(abc.ABC): + """Abstract transport class for TraceService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ) + + def __init__( + self, + *, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_write_spans: gapic_v1.method.wrap_method( + self.batch_write_spans, default_timeout=120.0, client_info=client_info, + ), + self.create_span: gapic_v1.method.wrap_method( + self.create_span, + default_retry=retries.Retry( + initial=0.1, + maximum=1.0, + multiplier=1.2, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=120.0, + client_info=client_info, + ), + } + + @property + def batch_write_spans( + self, + ) -> typing.Callable[ + [tracing.BatchWriteSpansRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_span( + self, + ) -> typing.Callable[ + [trace.Span], typing.Union[trace.Span, typing.Awaitable[trace.Span]] + ]: + raise NotImplementedError() + + +__all__ = ("TraceServiceTransport",) diff --git a/google/cloud/trace_v2/services/trace_service/transports/grpc.py b/google/cloud/trace_v2/services/trace_service/transports/grpc.py new file mode 100644 index 00000000..3bd20e4f --- /dev/null +++ b/google/cloud/trace_v2/services/trace_service/transports/grpc.py @@ -0,0 +1,273 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.trace_v2.types import trace +from google.cloud.trace_v2.types import tracing +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import TraceServiceTransport, DEFAULT_CLIENT_INFO + + +class TraceServiceGrpcTransport(TraceServiceTransport): + """gRPC backend transport for TraceService. + + This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. A single trace may contain span(s) from + multiple services. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def batch_write_spans( + self, + ) -> Callable[[tracing.BatchWriteSpansRequest], empty.Empty]: + r"""Return a callable for the batch write spans method over gRPC. + + Sends new spans to new or existing traces. You cannot + update existing spans. + + Returns: + Callable[[~.BatchWriteSpansRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_write_spans" not in self._stubs: + self._stubs["batch_write_spans"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans", + request_serializer=tracing.BatchWriteSpansRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["batch_write_spans"] + + @property + def create_span(self) -> Callable[[trace.Span], trace.Span]: + r"""Return a callable for the create span method over gRPC. + + Creates a new span. + + Returns: + Callable[[~.Span], + ~.Span]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_span" not in self._stubs: + self._stubs["create_span"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/CreateSpan", + request_serializer=trace.Span.serialize, + response_deserializer=trace.Span.deserialize, + ) + return self._stubs["create_span"] + + +__all__ = ("TraceServiceGrpcTransport",) diff --git a/google/cloud/trace_v2/services/trace_service/transports/grpc_asyncio.py b/google/cloud/trace_v2/services/trace_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..d40f19ee --- /dev/null +++ b/google/cloud/trace_v2/services/trace_service/transports/grpc_asyncio.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.trace_v2.types import trace +from google.cloud.trace_v2.types import tracing +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import TraceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TraceServiceGrpcTransport + + +class TraceServiceGrpcAsyncIOTransport(TraceServiceTransport): + """gRPC AsyncIO backend transport for TraceService. + + This file describes an API for collecting and viewing traces + and spans within a trace. A Trace is a collection of spans + corresponding to a single operation or set of operations for an + application. A span is an individual timed event which forms a + node of the trace tree. A single trace may contain span(s) from + multiple services. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudtrace.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def batch_write_spans( + self, + ) -> Callable[[tracing.BatchWriteSpansRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the batch write spans method over gRPC. + + Sends new spans to new or existing traces. You cannot + update existing spans. + + Returns: + Callable[[~.BatchWriteSpansRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_write_spans" not in self._stubs: + self._stubs["batch_write_spans"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans", + request_serializer=tracing.BatchWriteSpansRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["batch_write_spans"] + + @property + def create_span(self) -> Callable[[trace.Span], Awaitable[trace.Span]]: + r"""Return a callable for the create span method over gRPC. + + Creates a new span. + + Returns: + Callable[[~.Span], + Awaitable[~.Span]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_span" not in self._stubs: + self._stubs["create_span"] = self.grpc_channel.unary_unary( + "/google.devtools.cloudtrace.v2.TraceService/CreateSpan", + request_serializer=trace.Span.serialize, + response_deserializer=trace.Span.deserialize, + ) + return self._stubs["create_span"] + + +__all__ = ("TraceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/trace_v2/types.py b/google/cloud/trace_v2/types.py deleted file mode 100644 index ddbb681b..00000000 --- a/google/cloud/trace_v2/types.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.trace_v2.proto import trace_pb2 -from google.cloud.trace_v2.proto import tracing_pb2 -from google.protobuf import any_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 -from google.protobuf import wrappers_pb2 -from google.rpc import status_pb2 - - -_shared_modules = [ - any_pb2, - empty_pb2, - timestamp_pb2, - wrappers_pb2, - status_pb2, -] - -_local_modules = [ - trace_pb2, - tracing_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.trace_v2.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/trace_v2/types/__init__.py b/google/cloud/trace_v2/types/__init__.py new file mode 100644 index 00000000..4b94729a --- /dev/null +++ b/google/cloud/trace_v2/types/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .trace import ( + Span, + AttributeValue, + StackTrace, + Module, + TruncatableString, +) +from .tracing import BatchWriteSpansRequest + + +__all__ = ( + "Span", + "AttributeValue", + "StackTrace", + "Module", + "TruncatableString", + "BatchWriteSpansRequest", +) diff --git a/google/cloud/trace_v2/types/trace.py b/google/cloud/trace_v2/types/trace.py new file mode 100644 index 00000000..ab8773bb --- /dev/null +++ b/google/cloud/trace_v2/types/trace.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import wrappers_pb2 as wrappers # type: ignore +from google.rpc import status_pb2 as gr_status # type: ignore + + +__protobuf__ = proto.module( + package="google.devtools.cloudtrace.v2", + manifest={"Span", "AttributeValue", "StackTrace", "Module", "TruncatableString",}, +) + + +class Span(proto.Message): + r"""A span represents a single operation within a trace. Spans + can be nested to form a trace tree. Often, a trace contains a + root span that describes the end-to-end latency, and one or more + subspans for its sub-operations. A trace can also contain + multiple root spans, or none at all. Spans do not need to be + contiguous—there may be gaps or overlaps between spans in + a trace. + + Attributes: + name (str): + Required. The resource name of the span in the following + format: + + :: + + projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] + + [TRACE_ID] is a unique identifier for a trace within a + project; it is a 32-character hexadecimal encoding of a + 16-byte array. + + [SPAN_ID] is a unique identifier for a span within a trace; + it is a 16-character hexadecimal encoding of an 8-byte + array. + span_id (str): + Required. The [SPAN_ID] portion of the span's resource name. + parent_span_id (str): + The [SPAN_ID] of this span's parent span. If this is a root + span, then this field must be empty. + display_name (~.trace.TruncatableString): + Required. A description of the span's + operation (up to 128 bytes). Stackdriver Trace + displays the description in the Google Cloud + Platform Console. + For example, the display name can be a qualified + method name or a file name and a line number + where the operation is called. A best practice + is to use the same display name within an + application and at the same call point. This + makes it easier to correlate spans in different + traces. + start_time (~.timestamp.Timestamp): + Required. The start time of the span. On the + client side, this is the time kept by the local + machine where the span execution starts. On the + server side, this is the time when the server's + application handler starts running. + end_time (~.timestamp.Timestamp): + Required. The end time of the span. On the + client side, this is the time kept by the local + machine where the span execution ends. On the + server side, this is the time when the server + application handler stops running. + attributes (~.trace.Span.Attributes): + A set of attributes on the span. You can have + up to 32 attributes per span. + stack_trace (~.trace.StackTrace): + Stack trace captured at the start of the + span. + time_events (~.trace.Span.TimeEvents): + A set of time events. You can have up to 32 + annotations and 128 message events per span. + links (~.trace.Span.Links): + Links associated with the span. You can have + up to 128 links per Span. + status (~.gr_status.Status): + Optional. The final status for this span. + same_process_as_parent_span (~.wrappers.BoolValue): + Optional. Set this parameter to indicate + whether this span is in the same process as its + parent. If you do not set this parameter, + Stackdriver Trace is unable to take advantage of + this helpful information. + child_span_count (~.wrappers.Int32Value): + Optional. The number of child spans that were + generated while this span was active. If set, + allows implementation to detect missing child + spans. + span_kind (~.trace.Span.SpanKind): + Optional. Distinguishes between spans generated in a + particular context. For example, two spans with the same + name may be distinguished using ``CLIENT`` (caller) and + ``SERVER`` (callee) to identify an RPC call. + """ + + class SpanKind(proto.Enum): + r"""Type of span. Can be used to specify additional relationships + between spans in addition to a parent/child relationship. + """ + SPAN_KIND_UNSPECIFIED = 0 + INTERNAL = 1 + SERVER = 2 + CLIENT = 3 + PRODUCER = 4 + CONSUMER = 5 + + class Attributes(proto.Message): + r"""A set of attributes, each in the format ``[KEY]:[VALUE]``. + + Attributes: + attribute_map (Sequence[~.trace.Span.Attributes.AttributeMapEntry]): + The set of attributes. Each attribute's key can be up to 128 + bytes long. The value can be a string up to 256 bytes, a + signed 64-bit integer, or the Boolean values ``true`` and + ``false``. For example: + + :: + + "/instance_id": { "string_value": { "value": "my-instance" } } + "/http/request_bytes": { "int_value": 300 } + "abc.com/myattribute": { "bool_value": false } + dropped_attributes_count (int): + The number of attributes that were discarded. + Attributes can be discarded because their keys + are too long or because there are too many + attributes. If this value is 0 then all + attributes are valid. + """ + + attribute_map = proto.MapField( + proto.STRING, proto.MESSAGE, number=1, message="AttributeValue", + ) + + dropped_attributes_count = proto.Field(proto.INT32, number=2) + + class TimeEvent(proto.Message): + r"""A time-stamped annotation or message event in the Span. + + Attributes: + time (~.timestamp.Timestamp): + The timestamp indicating the time the event + occurred. + annotation (~.trace.Span.TimeEvent.Annotation): + Text annotation with a set of attributes. + message_event (~.trace.Span.TimeEvent.MessageEvent): + An event describing a message sent/received + between Spans. + """ + + class Annotation(proto.Message): + r"""Text annotation with a set of attributes. + + Attributes: + description (~.trace.TruncatableString): + A user-supplied message describing the event. + The maximum length for the description is 256 + bytes. + attributes (~.trace.Span.Attributes): + A set of attributes on the annotation. You + can have up to 4 attributes per Annotation. + """ + + description = proto.Field( + proto.MESSAGE, number=1, message="TruncatableString", + ) + + attributes = proto.Field( + proto.MESSAGE, number=2, message="Span.Attributes", + ) + + class MessageEvent(proto.Message): + r"""An event describing a message sent/received between Spans. + + Attributes: + type (~.trace.Span.TimeEvent.MessageEvent.Type): + Type of MessageEvent. Indicates whether the + message was sent or received. + id (int): + An identifier for the MessageEvent's message + that can be used to match SENT and RECEIVED + MessageEvents. It is recommended to be unique + within a Span. + uncompressed_size_bytes (int): + The number of uncompressed bytes sent or + received. + compressed_size_bytes (int): + The number of compressed bytes sent or + received. If missing assumed to be the same size + as uncompressed. + """ + + class Type(proto.Enum): + r"""Indicates whether the message was sent or received.""" + TYPE_UNSPECIFIED = 0 + SENT = 1 + RECEIVED = 2 + + type = proto.Field( + proto.ENUM, number=1, enum="Span.TimeEvent.MessageEvent.Type", + ) + + id = proto.Field(proto.INT64, number=2) + + uncompressed_size_bytes = proto.Field(proto.INT64, number=3) + + compressed_size_bytes = proto.Field(proto.INT64, number=4) + + time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + annotation = proto.Field( + proto.MESSAGE, number=2, oneof="value", message="Span.TimeEvent.Annotation", + ) + + message_event = proto.Field( + proto.MESSAGE, + number=3, + oneof="value", + message="Span.TimeEvent.MessageEvent", + ) + + class TimeEvents(proto.Message): + r"""A collection of ``TimeEvent``\ s. A ``TimeEvent`` is a time-stamped + annotation on the span, consisting of either user-supplied key:value + pairs, or details of a message sent/received between Spans. + + Attributes: + time_event (Sequence[~.trace.Span.TimeEvent]): + A collection of ``TimeEvent``\ s. + dropped_annotations_count (int): + The number of dropped annotations in all the + included time events. If the value is 0, then no + annotations were dropped. + dropped_message_events_count (int): + The number of dropped message events in all + the included time events. If the value is 0, + then no message events were dropped. + """ + + time_event = proto.RepeatedField( + proto.MESSAGE, number=1, message="Span.TimeEvent", + ) + + dropped_annotations_count = proto.Field(proto.INT32, number=2) + + dropped_message_events_count = proto.Field(proto.INT32, number=3) + + class Link(proto.Message): + r"""A pointer from the current span to another span in the same + trace or in a different trace. For example, this can be used in + batching operations, where a single batch handler processes + multiple requests from different traces or when the handler + receives a request from a different project. + + Attributes: + trace_id (str): + The [TRACE_ID] for a trace within a project. + span_id (str): + The [SPAN_ID] for a span within a trace. + type (~.trace.Span.Link.Type): + The relationship of the current span relative + to the linked span. + attributes (~.trace.Span.Attributes): + A set of attributes on the link. You have + have up to 32 attributes per link. + """ + + class Type(proto.Enum): + r"""The relationship of the current span relative to the linked + span: child, parent, or unspecified. + """ + TYPE_UNSPECIFIED = 0 + CHILD_LINKED_SPAN = 1 + PARENT_LINKED_SPAN = 2 + + trace_id = proto.Field(proto.STRING, number=1) + + span_id = proto.Field(proto.STRING, number=2) + + type = proto.Field(proto.ENUM, number=3, enum="Span.Link.Type",) + + attributes = proto.Field(proto.MESSAGE, number=4, message="Span.Attributes",) + + class Links(proto.Message): + r"""A collection of links, which are references from this span to + a span in the same or different trace. + + Attributes: + link (Sequence[~.trace.Span.Link]): + A collection of links. + dropped_links_count (int): + The number of dropped links after the maximum + size was enforced. If this value is 0, then no + links were dropped. + """ + + link = proto.RepeatedField(proto.MESSAGE, number=1, message="Span.Link",) + + dropped_links_count = proto.Field(proto.INT32, number=2) + + name = proto.Field(proto.STRING, number=1) + + span_id = proto.Field(proto.STRING, number=2) + + parent_span_id = proto.Field(proto.STRING, number=3) + + display_name = proto.Field(proto.MESSAGE, number=4, message="TruncatableString",) + + start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + + attributes = proto.Field(proto.MESSAGE, number=7, message=Attributes,) + + stack_trace = proto.Field(proto.MESSAGE, number=8, message="StackTrace",) + + time_events = proto.Field(proto.MESSAGE, number=9, message=TimeEvents,) + + links = proto.Field(proto.MESSAGE, number=10, message=Links,) + + status = proto.Field(proto.MESSAGE, number=11, message=gr_status.Status,) + + same_process_as_parent_span = proto.Field( + proto.MESSAGE, number=12, message=wrappers.BoolValue, + ) + + child_span_count = proto.Field( + proto.MESSAGE, number=13, message=wrappers.Int32Value, + ) + + span_kind = proto.Field(proto.ENUM, number=14, enum=SpanKind,) + + +class AttributeValue(proto.Message): + r"""The allowed types for [VALUE] in a ``[KEY]:[VALUE]`` attribute. + + Attributes: + string_value (~.trace.TruncatableString): + A string up to 256 bytes long. + int_value (int): + A 64-bit signed integer. + bool_value (bool): + A Boolean value represented by ``true`` or ``false``. + """ + + string_value = proto.Field( + proto.MESSAGE, number=1, oneof="value", message="TruncatableString", + ) + + int_value = proto.Field(proto.INT64, number=2, oneof="value") + + bool_value = proto.Field(proto.BOOL, number=3, oneof="value") + + +class StackTrace(proto.Message): + r"""A call stack appearing in a trace. + + Attributes: + stack_frames (~.trace.StackTrace.StackFrames): + Stack frames in this stack trace. A maximum + of 128 frames are allowed. + stack_trace_hash_id (int): + The hash ID is used to conserve network bandwidth for + duplicate stack traces within a single trace. + + Often multiple spans will have identical stack traces. The + first occurrence of a stack trace should contain both the + ``stackFrame`` content and a value in ``stackTraceHashId``. + + Subsequent spans within the same request can refer to that + stack trace by only setting ``stackTraceHashId``. + """ + + class StackFrame(proto.Message): + r"""Represents a single stack frame in a stack trace. + + Attributes: + function_name (~.trace.TruncatableString): + The fully-qualified name that uniquely + identifies the function or method that is active + in this frame (up to 1024 bytes). + original_function_name (~.trace.TruncatableString): + An un-mangled function name, if ``function_name`` is + `mangled `__. + The name can be fully-qualified (up to 1024 bytes). + file_name (~.trace.TruncatableString): + The name of the source file where the + function call appears (up to 256 bytes). + line_number (int): + The line number in ``file_name`` where the function call + appears. + column_number (int): + The column number where the function call + appears, if available. This is important in + JavaScript because of its anonymous functions. + load_module (~.trace.Module): + The binary module from where the code was + loaded. + source_version (~.trace.TruncatableString): + The version of the deployed source code (up + to 128 bytes). + """ + + function_name = proto.Field( + proto.MESSAGE, number=1, message="TruncatableString", + ) + + original_function_name = proto.Field( + proto.MESSAGE, number=2, message="TruncatableString", + ) + + file_name = proto.Field(proto.MESSAGE, number=3, message="TruncatableString",) + + line_number = proto.Field(proto.INT64, number=4) + + column_number = proto.Field(proto.INT64, number=5) + + load_module = proto.Field(proto.MESSAGE, number=6, message="Module",) + + source_version = proto.Field( + proto.MESSAGE, number=7, message="TruncatableString", + ) + + class StackFrames(proto.Message): + r"""A collection of stack frames, which can be truncated. + + Attributes: + frame (Sequence[~.trace.StackTrace.StackFrame]): + Stack frames in this call stack. + dropped_frames_count (int): + The number of stack frames that were dropped + because there were too many stack frames. + If this value is 0, then no stack frames were + dropped. + """ + + frame = proto.RepeatedField( + proto.MESSAGE, number=1, message="StackTrace.StackFrame", + ) + + dropped_frames_count = proto.Field(proto.INT32, number=2) + + stack_frames = proto.Field(proto.MESSAGE, number=1, message=StackFrames,) + + stack_trace_hash_id = proto.Field(proto.INT64, number=2) + + +class Module(proto.Message): + r"""Binary module. + + Attributes: + module (~.trace.TruncatableString): + For example: main binary, kernel modules, and + dynamic libraries such as libc.so, sharedlib.so + (up to 256 bytes). + build_id (~.trace.TruncatableString): + A unique identifier for the module, usually a + hash of its contents (up to 128 bytes). + """ + + module = proto.Field(proto.MESSAGE, number=1, message="TruncatableString",) + + build_id = proto.Field(proto.MESSAGE, number=2, message="TruncatableString",) + + +class TruncatableString(proto.Message): + r"""Represents a string that might be shortened to a specified + length. + + Attributes: + value (str): + The shortened string. For example, if the original string is + 500 bytes long and the limit of the string is 128 bytes, + then ``value`` contains the first 128 bytes of the 500-byte + string. + + Truncation always happens on a UTF8 character boundary. If + there are multi-byte characters in the string, then the + length of the shortened string might be less than the size + limit. + truncated_byte_count (int): + The number of bytes removed from the original + string. If this value is 0, then the string was + not shortened. + """ + + value = proto.Field(proto.STRING, number=1) + + truncated_byte_count = proto.Field(proto.INT32, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/trace_v2/types/tracing.py b/google/cloud/trace_v2/types/tracing.py new file mode 100644 index 00000000..b2eaff79 --- /dev/null +++ b/google/cloud/trace_v2/types/tracing.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.trace_v2.types import trace + + +__protobuf__ = proto.module( + package="google.devtools.cloudtrace.v2", manifest={"BatchWriteSpansRequest",}, +) + + +class BatchWriteSpansRequest(proto.Message): + r"""The request message for the ``BatchWriteSpans`` method. + + Attributes: + name (str): + Required. The name of the project where the spans belong. + The format is ``projects/[PROJECT_ID]``. + spans (Sequence[~.trace.Span]): + Required. A list of new spans. The span names + must not match existing spans, or the results + are undefined. + """ + + name = proto.Field(proto.STRING, number=1) + + spans = proto.RepeatedField(proto.MESSAGE, number=2, message=trace.Span,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index 1142ec19..090ed4b4 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -139,7 +141,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=98") + session.run("coverage", "report", "--show-missing", "--fail-under=100") session.run("coverage", "erase") @@ -149,7 +151,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") + session.install("sphinx", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -171,7 +173,7 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark", "sphinx-docfx-yaml") + session.install("sphinx", "alabaster", "recommonmark", "sphinx-docfx-yaml") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/samples/AUTHORING_GUIDE.md b/samples/AUTHORING_GUIDE.md new file mode 100644 index 00000000..55c97b32 --- /dev/null +++ b/samples/AUTHORING_GUIDE.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/samples/CONTRIBUTING.md b/samples/CONTRIBUTING.md new file mode 100644 index 00000000..34c882b6 --- /dev/null +++ b/samples/CONTRIBUTING.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/samples/snippets/batch_write_spans.py b/samples/snippets/batch_write_spans.py new file mode 100644 index 00000000..965f5f88 --- /dev/null +++ b/samples/snippets/batch_write_spans.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +import uuid + +from google.cloud import trace_v2 + + +def batch_write_spans(project_id: str): + """Send new spans to new or existing traces.""" + + client = trace_v2.TraceServiceClient() + + display_name = trace_v2.TruncatableString(value="Test Span Display Name") + trace_id = str(uuid.uuid4()).replace("-", "") + span_id = str(uuid.uuid4()).replace("-", "")[:16] + + end_time = datetime.datetime.now() + start_time = end_time - datetime.timedelta(seconds=5) + + # Create a single span + span = trace_v2.Span( + name=client.span_path(project_id, trace_id, span_id), + span_id=span_id, + display_name=display_name, + start_time=start_time, + end_time=end_time, + ) + + client.batch_write_spans(name=f"projects/{project_id}", spans=[span]) diff --git a/samples/snippets/batch_write_spans_test.py b/samples/snippets/batch_write_spans_test.py new file mode 100644 index 00000000..b414ca50 --- /dev/null +++ b/samples/snippets/batch_write_spans_test.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import batch_write_spans + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_get_trace(): + batch_write_spans.batch_write_spans(project_id=PROJECT_ID) diff --git a/samples/snippets/create_span.py b/samples/snippets/create_span.py new file mode 100644 index 00000000..6e4d1cc6 --- /dev/null +++ b/samples/snippets/create_span.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime + +from google.cloud import trace_v2 + + +def create_span( + project_id: str, + trace_id: str, + span_id: str, + display_name: str, + start_time: datetime.datetime, + end_time: datetime.datetime, +): + """Create a new span. + + Args: + project_id: The name of the project. + trace_id: A unique identifier for a trace within a + project; it is a 32-character hexadecimal encoding of a + 16-byte array. + span_id: A unique identifier for a span within a trace; + it is a 16-character hexadecimal encoding of an 8-byte + display_name: A description of the span's + operation (up to 128 bytes) + start_time: The start time of the span. + end_time: The end time of the span. + """ + + client = trace_v2.TraceServiceClient() + + name = client.span_path(project_id, trace_id, span_id) + display_name = trace_v2.TruncatableString(value=display_name) + + request = trace_v2.Span( + name=name, + span_id=span_id, + display_name=display_name, + start_time=start_time, + end_time=end_time, + ) + + span = client.create_span(request=request) + + print(span) + return span diff --git a/samples/snippets/create_span_test.py b/samples/snippets/create_span_test.py new file mode 100644 index 00000000..a419a80c --- /dev/null +++ b/samples/snippets/create_span_test.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +import os +import uuid + +import create_span + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_get_trace(): + trace_id = str(uuid.uuid4()).replace("-", "") + span_id = str(uuid.uuid4()).replace("-", "")[:16] + end_time = datetime.datetime.now() + start_time = end_time - datetime.timedelta(seconds=5) + + span = create_span.create_span( + project_id=PROJECT_ID, + trace_id=trace_id, + span_id=span_id, + display_name="test", + start_time=start_time, + end_time=end_time, + ) + + assert span.name == f"projects/{PROJECT_ID}/traces/{trace_id}/spans/{span_id}" diff --git a/samples/snippets/get_trace.py b/samples/snippets/get_trace.py new file mode 100644 index 00000000..edfe0145 --- /dev/null +++ b/samples/snippets/get_trace.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from google.cloud import trace_v1 + + +def get_trace(project_id: str, trace_id: str): + """Get a trace by its ID.""" + + client = trace_v1.TraceServiceClient() + + trace = client.get_trace(project_id=project_id, trace_id=trace_id) + + print(trace) + return trace diff --git a/samples/snippets/get_trace_test.py b/samples/snippets/get_trace_test.py new file mode 100644 index 00000000..304c23b6 --- /dev/null +++ b/samples/snippets/get_trace_test.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +from google.cloud import trace_v1 +import pytest + +import get_trace + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +@pytest.fixture(scope="module") +def trace_id(): + # list all traces in the project and return the first + client = trace_v1.TraceServiceClient() + traces = client.list_traces(project_id=PROJECT_ID) + + return list(traces)[0].trace_id + + +def test_get_trace(trace_id): + get_trace.get_trace(project_id=PROJECT_ID, trace_id=trace_id) diff --git a/samples/snippets/list_traces.py b/samples/snippets/list_traces.py new file mode 100644 index 00000000..6e1701ed --- /dev/null +++ b/samples/snippets/list_traces.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from google.cloud import trace_v1 + + +def list_traces(project_id: str): + """List traces for a project.""" + + client = trace_v1.TraceServiceClient() + + request = trace_v1.ListTracesRequest(project_id=project_id) + traces = client.list_traces(request=request) + + for trace in traces: + print(trace) + + return traces diff --git a/samples/snippets/list_traces_test.py b/samples/snippets/list_traces_test.py new file mode 100644 index 00000000..380fe37a --- /dev/null +++ b/samples/snippets/list_traces_test.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import list_traces + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_list_traces(): + traces = list_traces.list_traces(project_id=PROJECT_ID) + assert len(list(traces)) > 1 diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py new file mode 100644 index 00000000..5660f08b --- /dev/null +++ b/samples/snippets/noxfile.py @@ -0,0 +1,222 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import print_function + +import os +from pathlib import Path +import sys + +import nox + + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +# Copy `noxfile_config.py` to your directory and modify it instead. + + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7"], + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append(".") + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars(): + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG["gcloud_project_env"] + # This should error out if not set. + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] + + # Apply user supplied envs. + ret.update(TEST_CONFIG["envs"]) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to tested samples. +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +# +# Style Checks +# + + +def _determine_local_import_names(start_dir): + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--import-order-style=google", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session): + session.install("flake8", "flake8-import-order") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + ".", + ] + session.run("flake8", *args) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests(session, post_install=None): + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars() + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session): + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) + + +# +# Readmegen +# + + +def _get_repo_root(): + """ Returns the root folder of the project. """ + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session, path): + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/samples/snippets/patch_traces.py b/samples/snippets/patch_traces.py new file mode 100644 index 00000000..6a379e7d --- /dev/null +++ b/samples/snippets/patch_traces.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import uuid + +from google.cloud import trace_v1 + + +def patch_traces(project_id: str): + """Send new traces or update existing traces.""" + + client = trace_v1.TraceServiceClient() + + trace = trace_v1.Trace( + project_id=project_id, + trace_id=str(uuid.uuid4()).replace("-", ""), + spans=[trace_v1.TraceSpan(span_id=1, name="test-span")], + ) + + request = trace_v1.PatchTracesRequest( + project_id=project_id, traces=trace_v1.Traces(traces=[trace]) + ) + + client.patch_traces(request=request) diff --git a/samples/snippets/patch_traces_test.py b/samples/snippets/patch_traces_test.py new file mode 100644 index 00000000..b031ae7e --- /dev/null +++ b/samples/snippets/patch_traces_test.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +from google.cloud import trace_v1 +import pytest + +import patch_traces + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +@pytest.fixture(scope="module") +def trace_id(): + # list all traces in the project and return the first + client = trace_v1.TraceServiceClient() + traces = client.list_traces(project_id=PROJECT_ID) + + return list(traces)[0].trace_id + + +def test_patch_traces(): + patch_traces.patch_traces(project_id=PROJECT_ID) diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt new file mode 100644 index 00000000..3413ad1c --- /dev/null +++ b/samples/snippets/requirements-test.txt @@ -0,0 +1 @@ +pytest==6.0.1 \ No newline at end of file diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt new file mode 100644 index 00000000..d751e7d3 --- /dev/null +++ b/samples/snippets/requirements.txt @@ -0,0 +1 @@ +google-cloud-trace==0.23.0 \ No newline at end of file diff --git a/scripts/fixup_trace_v1_keywords.py b/scripts/fixup_trace_v1_keywords.py new file mode 100644 index 00000000..71a02d87 --- /dev/null +++ b/scripts/fixup_trace_v1_keywords.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class traceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'get_trace': ('project_id', 'trace_id', ), + 'list_traces': ('project_id', 'view', 'page_size', 'page_token', 'start_time', 'end_time', 'filter', 'order_by', ), + 'patch_traces': ('project_id', 'traces', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=traceCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the trace client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_trace_v2_keywords.py b/scripts/fixup_trace_v2_keywords.py new file mode 100644 index 00000000..f01c1004 --- /dev/null +++ b/scripts/fixup_trace_v2_keywords.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class traceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_write_spans': ('name', 'spans', ), + 'create_span': ('name', 'span_id', 'display_name', 'start_time', 'end_time', 'parent_span_id', 'attributes', 'stack_trace', 'time_events', 'links', 'status', 'same_process_as_parent_span', 'child_span_count', 'span_kind', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=traceCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the trace client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index 3f506cdf..b28c9d7d 100644 --- a/setup.py +++ b/setup.py @@ -29,8 +29,9 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 3 - Alpha" dependencies = [ - "google-api-core[grpc] >= 1.14.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "google-cloud-core >= 1.0.3, < 2.0dev", + "proto-plus >= 1.4.0", ] extras = {} @@ -46,7 +47,9 @@ # Only include packages under the 'google' namespace. Do not include tests, # benchmarks, etc. packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] # Determine which namespaces are needed. @@ -69,12 +72,9 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -83,7 +83,11 @@ namespace_packages=namespaces, install_requires=dependencies, extras_require=extras, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", + scripts=[ + "scripts/fixup_trace_v1_keywords.py", + "scripts/fixup_trace_v2_keywords.py", + ], include_package_data=True, zip_safe=False, ) diff --git a/synth.metadata b/synth.metadata index f6c716bf..2e2dbd35 100644 --- a/synth.metadata +++ b/synth.metadata @@ -9,10 +9,9 @@ }, { "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "db69b46790b55a82ab7cfa473d031da787bc7591", - "internalRef": "320411362" + "name": "synthtool", + "remote": "https://github.com/googleapis/synthtool.git", + "sha": "05de3e1e14a0b07eab8b474e669164dbd31f81fb" } }, { diff --git a/synth.py b/synth.py index ebb7f061..982a2bb7 100644 --- a/synth.py +++ b/synth.py @@ -14,6 +14,7 @@ """This script is used to synthesize generated parts of this library.""" +from synthtool.languages import python import synthtool as s import synthtool.gcp as gcp @@ -32,34 +33,18 @@ include_protos=True, ) - s.move(library / f"google/cloud/trace_{version}") - s.move(library / f"tests/unit/gapic/{version}") - s.move(library/ f"google/cloud/devtools/cloudtrace_{version}/proto", - f"google/cloud/trace_{version}/proto") + s.move(library, excludes=["docs/index.rst", "setup.py"]) - # Fix up imports - s.replace( - "google/**/*.py", - f"from google.cloud.devtools.cloudtrace_{version}.proto import ", - f"from google.cloud.trace_{version}.proto import ", - ) - - s.replace( - f"google/cloud/trace_{version}/gapic/trace_service_client.py", - "google-cloud-devtools-cloudtrace", - "google-cloud-trace", - ) - -# Copy docs configuration -s.move(library / f"docs/conf.py") # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=98) -s.move(templated_files) +templated_files = common.py_library( + samples=True, # set to True only if there are samples + microgenerator=True, +) -# TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", '''['"]sphinx["']''', '"sphinx<3.0.0"') +python.py_samples(skip_readmes=True) +s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/tests/system/gapic/v1/test_system_trace_service_v1.py b/tests/system/gapic/v1/test_system_trace_service_v1.py index bfdba136..d6bc7a78 100644 --- a/tests/system/gapic/v1/test_system_trace_service_v1.py +++ b/tests/system/gapic/v1/test_system_trace_service_v1.py @@ -16,9 +16,6 @@ import time from google.cloud import trace_v1 -from google.cloud.trace_v1 import enums -from google.cloud.trace_v1.proto import trace_pb2 -from google.protobuf import timestamp_pb2 class TestSystemTraceService(object): @@ -27,4 +24,4 @@ def test_list_traces(self): client = trace_v1.TraceServiceClient() project_id_2 = project_id - response = client.list_traces(project_id_2) + response = client.list_traces(project_id=project_id_2) diff --git a/tests/system/gapic/v1/test_system_trace_service_v1_vpcsc.py b/tests/system/gapic/v1/test_system_trace_service_v1_vpcsc.py index 69aeaaf8..4fd73811 100644 --- a/tests/system/gapic/v1/test_system_trace_service_v1_vpcsc.py +++ b/tests/system/gapic/v1/test_system_trace_service_v1_vpcsc.py @@ -33,13 +33,13 @@ def client(): @vpcsc_config.skip_unless_inside_vpcsc def test_list_traces_w_inside(client): - list(client.list_traces(vpcsc_config.project_inside)) # no perms issue + list(client.list_traces(project_id=vpcsc_config.project_inside)) # no perms issue @vpcsc_config.skip_unless_inside_vpcsc def test_list_traces_w_outside(client): with pytest.raises(exceptions.PermissionDenied) as exc: - list(client.list_traces(vpcsc_config.project_outside)) + list(client.list_traces(project_id=vpcsc_config.project_outside)) assert _VPCSC_PROHIBITED_MESSAGE in exc.value.message @@ -47,13 +47,15 @@ def test_list_traces_w_outside(client): @vpcsc_config.skip_unless_inside_vpcsc def test_get_trace_w_inside(client): with pytest.raises(exceptions.InvalidArgument): - client.get_trace(vpcsc_config.project_inside, "") # no perms issue + client.get_trace( + project_id=vpcsc_config.project_inside, trace_id="" + ) # no perms issue @vpcsc_config.skip_unless_inside_vpcsc def test_get_trace_w_outside(client): with pytest.raises(exceptions.PermissionDenied) as exc: - client.get_trace(vpcsc_config.project_outside, "") + client.get_trace(project_id=vpcsc_config.project_outside, trace_id="") assert _VPCSC_PROHIBITED_MESSAGE in exc.value.message @@ -61,12 +63,14 @@ def test_get_trace_w_outside(client): @vpcsc_config.skip_unless_inside_vpcsc def test_patch_traces_w_inside(client): with pytest.raises(exceptions.InvalidArgument): - client.patch_traces(vpcsc_config.project_inside, {}) # no perms issue + client.patch_traces( + project_id=vpcsc_config.project_inside, traces={} + ) # no perms issue @vpcsc_config.skip_unless_inside_vpcsc def test_patch_traces_w_ouside(client): with pytest.raises(exceptions.PermissionDenied) as exc: - client.patch_traces(vpcsc_config.project_outside, {}) + client.patch_traces(project_id=vpcsc_config.project_outside, traces={}) assert _VPCSC_PROHIBITED_MESSAGE in exc.value.message diff --git a/tests/system/gapic/v2/test_system_trace_service_v2.py b/tests/system/gapic/v2/test_system_trace_service_v2.py index fb42ca7b..0a73506a 100644 --- a/tests/system/gapic/v2/test_system_trace_service_v2.py +++ b/tests/system/gapic/v2/test_system_trace_service_v2.py @@ -16,8 +16,6 @@ import time from google.cloud import trace_v2 -from google.cloud.trace_v2.proto import trace_pb2 -from google.cloud.trace_v2.proto import tracing_pb2 class TestSystemTraceService(object): @@ -25,6 +23,6 @@ def test_batch_write_spans(self): project_id = os.environ["PROJECT_ID"] client = trace_v2.TraceServiceClient() - name = client.project_path(project_id) + name = f"projects/{project_id}" spans = [] - client.batch_write_spans(name, spans) + client.batch_write_spans(name=name, spans=spans) diff --git a/tests/system/gapic/v2/test_system_trace_service_v2_vpcsc.py b/tests/system/gapic/v2/test_system_trace_service_v2_vpcsc.py index 19add188..a373ba51 100644 --- a/tests/system/gapic/v2/test_system_trace_service_v2_vpcsc.py +++ b/tests/system/gapic/v2/test_system_trace_service_v2_vpcsc.py @@ -33,15 +33,15 @@ def client(): @vpcsc_config.skip_unless_inside_vpcsc def test_batch_write_spans_w_inside(client): - project_inside = client.project_path(vpcsc_config.project_inside) - client.batch_write_spans(project_inside, []) # no raise + project_inside = f"projects/{vpcsc_config.project_inside}" + client.batch_write_spans(name=project_inside, spans=[]) # no raise @vpcsc_config.skip_unless_inside_vpcsc def test_batch_write_spans_w_outside(client): - project_outside = client.project_path(vpcsc_config.project_outside) + project_outside = f"projects/{vpcsc_config.project_outside}" with pytest.raises(exceptions.PermissionDenied) as exc: - client.batch_write_spans(project_outside, []) + client.batch_write_spans(name=project_outside, spans=[]) assert _VPCSC_PROHIBITED_MESSAGE in exc.value.message diff --git a/tests/unit/gapic/trace_v1/__init__.py b/tests/unit/gapic/trace_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/trace_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/trace_v1/test_trace_service.py b/tests/unit/gapic/trace_v1/test_trace_service.py new file mode 100644 index 00000000..c5883386 --- /dev/null +++ b/tests/unit/gapic/trace_v1/test_trace_service.py @@ -0,0 +1,1273 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.trace_v1.services.trace_service import TraceServiceAsyncClient +from google.cloud.trace_v1.services.trace_service import TraceServiceClient +from google.cloud.trace_v1.services.trace_service import pagers +from google.cloud.trace_v1.services.trace_service import transports +from google.cloud.trace_v1.types import trace +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert TraceServiceClient._get_default_mtls_endpoint(None) is None + assert ( + TraceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + TraceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + TraceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TraceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert TraceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [TraceServiceClient, TraceServiceAsyncClient]) +def test_trace_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudtrace.googleapis.com:443" + + +def test_trace_service_client_get_transport_class(): + transport = TraceServiceClient.get_transport_class() + assert transport == transports.TraceServiceGrpcTransport + + transport = TraceServiceClient.get_transport_class("grpc") + assert transport == transports.TraceServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"), + ( + TraceServiceAsyncClient, + transports.TraceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + TraceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TraceServiceClient) +) +@mock.patch.object( + TraceServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TraceServiceAsyncClient), +) +def test_trace_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(TraceServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(TraceServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"), + ( + TraceServiceAsyncClient, + transports.TraceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_trace_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"), + ( + TraceServiceAsyncClient, + transports.TraceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_trace_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_trace_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.trace_v1.services.trace_service.transports.TraceServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = TraceServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_traces(transport: str = "grpc", request_type=trace.ListTracesRequest): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_traces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = trace.ListTracesResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_traces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == trace.ListTracesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTracesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_traces_from_dict(): + test_list_traces(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_traces_async(transport: str = "grpc_asyncio"): + client = TraceServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = trace.ListTracesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_traces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + trace.ListTracesResponse(next_page_token="next_page_token_value",) + ) + + response = await client.list_traces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTracesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_traces_flattened(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_traces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = trace.ListTracesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_traces(project_id="project_id_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].project_id == "project_id_value" + + +def test_list_traces_flattened_error(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_traces( + trace.ListTracesRequest(), project_id="project_id_value", + ) + + +@pytest.mark.asyncio +async def test_list_traces_flattened_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_traces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = trace.ListTracesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + trace.ListTracesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_traces(project_id="project_id_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].project_id == "project_id_value" + + +@pytest.mark.asyncio +async def test_list_traces_flattened_error_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_traces( + trace.ListTracesRequest(), project_id="project_id_value", + ) + + +def test_list_traces_pager(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_traces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + trace.ListTracesResponse( + traces=[trace.Trace(), trace.Trace(), trace.Trace(),], + next_page_token="abc", + ), + trace.ListTracesResponse(traces=[], next_page_token="def",), + trace.ListTracesResponse(traces=[trace.Trace(),], next_page_token="ghi",), + trace.ListTracesResponse(traces=[trace.Trace(), trace.Trace(),],), + RuntimeError, + ) + + metadata = () + pager = client.list_traces(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, trace.Trace) for i in results) + + +def test_list_traces_pages(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_traces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + trace.ListTracesResponse( + traces=[trace.Trace(), trace.Trace(), trace.Trace(),], + next_page_token="abc", + ), + trace.ListTracesResponse(traces=[], next_page_token="def",), + trace.ListTracesResponse(traces=[trace.Trace(),], next_page_token="ghi",), + trace.ListTracesResponse(traces=[trace.Trace(), trace.Trace(),],), + RuntimeError, + ) + pages = list(client.list_traces(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_traces_async_pager(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_traces), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + trace.ListTracesResponse( + traces=[trace.Trace(), trace.Trace(), trace.Trace(),], + next_page_token="abc", + ), + trace.ListTracesResponse(traces=[], next_page_token="def",), + trace.ListTracesResponse(traces=[trace.Trace(),], next_page_token="ghi",), + trace.ListTracesResponse(traces=[trace.Trace(), trace.Trace(),],), + RuntimeError, + ) + async_pager = await client.list_traces(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, trace.Trace) for i in responses) + + +@pytest.mark.asyncio +async def test_list_traces_async_pages(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_traces), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + trace.ListTracesResponse( + traces=[trace.Trace(), trace.Trace(), trace.Trace(),], + next_page_token="abc", + ), + trace.ListTracesResponse(traces=[], next_page_token="def",), + trace.ListTracesResponse(traces=[trace.Trace(),], next_page_token="ghi",), + trace.ListTracesResponse(traces=[trace.Trace(), trace.Trace(),],), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_traces(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_trace(transport: str = "grpc", request_type=trace.GetTraceRequest): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_trace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = trace.Trace( + project_id="project_id_value", trace_id="trace_id_value", + ) + + response = client.get_trace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == trace.GetTraceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, trace.Trace) + + assert response.project_id == "project_id_value" + + assert response.trace_id == "trace_id_value" + + +def test_get_trace_from_dict(): + test_get_trace(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_trace_async(transport: str = "grpc_asyncio"): + client = TraceServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = trace.GetTraceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_trace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + trace.Trace(project_id="project_id_value", trace_id="trace_id_value",) + ) + + response = await client.get_trace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trace.Trace) + + assert response.project_id == "project_id_value" + + assert response.trace_id == "trace_id_value" + + +def test_get_trace_flattened(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_trace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = trace.Trace() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_trace( + project_id="project_id_value", trace_id="trace_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].project_id == "project_id_value" + + assert args[0].trace_id == "trace_id_value" + + +def test_get_trace_flattened_error(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_trace( + trace.GetTraceRequest(), + project_id="project_id_value", + trace_id="trace_id_value", + ) + + +@pytest.mark.asyncio +async def test_get_trace_flattened_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_trace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = trace.Trace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trace.Trace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_trace( + project_id="project_id_value", trace_id="trace_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].project_id == "project_id_value" + + assert args[0].trace_id == "trace_id_value" + + +@pytest.mark.asyncio +async def test_get_trace_flattened_error_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_trace( + trace.GetTraceRequest(), + project_id="project_id_value", + trace_id="trace_id_value", + ) + + +def test_patch_traces(transport: str = "grpc", request_type=trace.PatchTracesRequest): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.patch_traces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.patch_traces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == trace.PatchTracesRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_patch_traces_from_dict(): + test_patch_traces(request_type=dict) + + +@pytest.mark.asyncio +async def test_patch_traces_async(transport: str = "grpc_asyncio"): + client = TraceServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = trace.PatchTracesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.patch_traces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.patch_traces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_patch_traces_flattened(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.patch_traces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.patch_traces( + project_id="project_id_value", + traces=trace.Traces(traces=[trace.Trace(project_id="project_id_value")]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].project_id == "project_id_value" + + assert args[0].traces == trace.Traces( + traces=[trace.Trace(project_id="project_id_value")] + ) + + +def test_patch_traces_flattened_error(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.patch_traces( + trace.PatchTracesRequest(), + project_id="project_id_value", + traces=trace.Traces(traces=[trace.Trace(project_id="project_id_value")]), + ) + + +@pytest.mark.asyncio +async def test_patch_traces_flattened_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.patch_traces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.patch_traces( + project_id="project_id_value", + traces=trace.Traces(traces=[trace.Trace(project_id="project_id_value")]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].project_id == "project_id_value" + + assert args[0].traces == trace.Traces( + traces=[trace.Trace(project_id="project_id_value")] + ) + + +@pytest.mark.asyncio +async def test_patch_traces_flattened_error_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.patch_traces( + trace.PatchTracesRequest(), + project_id="project_id_value", + traces=trace.Traces(traces=[trace.Trace(project_id="project_id_value")]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TraceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TraceServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = TraceServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TraceServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.TraceServiceGrpcTransport,) + + +def test_trace_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.TraceServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_trace_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.trace_v1.services.trace_service.transports.TraceServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TraceServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_traces", + "get_trace", + "patch_traces", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_trace_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.trace_v1.services.trace_service.transports.TraceServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.TraceServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ), + quota_project_id="octopus", + ) + + +def test_trace_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + TraceServiceClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ), + quota_project_id=None, + ) + + +def test_trace_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ), + quota_project_id="octopus", + ) + + +def test_trace_service_host_no_port(): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudtrace.googleapis.com" + ), + ) + assert client._transport._host == "cloudtrace.googleapis.com:443" + + +def test_trace_service_host_with_port(): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudtrace.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudtrace.googleapis.com:8000" + + +def test_trace_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_trace_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TraceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_trace_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_trace_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TraceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_trace_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_trace_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TraceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + "https://www.googleapis.com/auth/trace.readonly", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.TraceServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.TraceServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = TraceServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/trace_v2/__init__.py b/tests/unit/gapic/trace_v2/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/trace_v2/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/trace_v2/test_trace_service.py b/tests/unit/gapic/trace_v2/test_trace_service.py new file mode 100644 index 00000000..9072a594 --- /dev/null +++ b/tests/unit/gapic/trace_v2/test_trace_service.py @@ -0,0 +1,1092 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.trace_v2.services.trace_service import TraceServiceAsyncClient +from google.cloud.trace_v2.services.trace_service import TraceServiceClient +from google.cloud.trace_v2.services.trace_service import transports +from google.cloud.trace_v2.types import trace +from google.cloud.trace_v2.types import tracing +from google.oauth2 import service_account +from google.protobuf import any_pb2 as any # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import wrappers_pb2 as wrappers # type: ignore +from google.rpc import status_pb2 as gr_status # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert TraceServiceClient._get_default_mtls_endpoint(None) is None + assert ( + TraceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + TraceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + TraceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TraceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert TraceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [TraceServiceClient, TraceServiceAsyncClient]) +def test_trace_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudtrace.googleapis.com:443" + + +def test_trace_service_client_get_transport_class(): + transport = TraceServiceClient.get_transport_class() + assert transport == transports.TraceServiceGrpcTransport + + transport = TraceServiceClient.get_transport_class("grpc") + assert transport == transports.TraceServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"), + ( + TraceServiceAsyncClient, + transports.TraceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + TraceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TraceServiceClient) +) +@mock.patch.object( + TraceServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TraceServiceAsyncClient), +) +def test_trace_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(TraceServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(TraceServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"), + ( + TraceServiceAsyncClient, + transports.TraceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_trace_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"), + ( + TraceServiceAsyncClient, + transports.TraceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_trace_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_trace_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.trace_v2.services.trace_service.transports.TraceServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = TraceServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_batch_write_spans( + transport: str = "grpc", request_type=tracing.BatchWriteSpansRequest +): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_write_spans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.batch_write_spans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == tracing.BatchWriteSpansRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_batch_write_spans_from_dict(): + test_batch_write_spans(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_write_spans_async(transport: str = "grpc_asyncio"): + client = TraceServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = tracing.BatchWriteSpansRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_write_spans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.batch_write_spans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_batch_write_spans_field_headers(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tracing.BatchWriteSpansRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_write_spans), "__call__" + ) as call: + call.return_value = None + + client.batch_write_spans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_write_spans_field_headers_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tracing.BatchWriteSpansRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_write_spans), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.batch_write_spans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_batch_write_spans_flattened(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_write_spans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_write_spans( + name="name_value", spans=[trace.Span(name="name_value")], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].spans == [trace.Span(name="name_value")] + + +def test_batch_write_spans_flattened_error(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_write_spans( + tracing.BatchWriteSpansRequest(), + name="name_value", + spans=[trace.Span(name="name_value")], + ) + + +@pytest.mark.asyncio +async def test_batch_write_spans_flattened_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_write_spans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_write_spans( + name="name_value", spans=[trace.Span(name="name_value")], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].spans == [trace.Span(name="name_value")] + + +@pytest.mark.asyncio +async def test_batch_write_spans_flattened_error_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_write_spans( + tracing.BatchWriteSpansRequest(), + name="name_value", + spans=[trace.Span(name="name_value")], + ) + + +def test_create_span(transport: str = "grpc", request_type=trace.Span): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_span), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = trace.Span( + name="name_value", + span_id="span_id_value", + parent_span_id="parent_span_id_value", + span_kind=trace.Span.SpanKind.INTERNAL, + ) + + response = client.create_span(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == trace.Span() + + # Establish that the response is the type that we expect. + assert isinstance(response, trace.Span) + + assert response.name == "name_value" + + assert response.span_id == "span_id_value" + + assert response.parent_span_id == "parent_span_id_value" + + assert response.span_kind == trace.Span.SpanKind.INTERNAL + + +def test_create_span_from_dict(): + test_create_span(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_span_async(transport: str = "grpc_asyncio"): + client = TraceServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = trace.Span() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_span), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + trace.Span( + name="name_value", + span_id="span_id_value", + parent_span_id="parent_span_id_value", + span_kind=trace.Span.SpanKind.INTERNAL, + ) + ) + + response = await client.create_span(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trace.Span) + + assert response.name == "name_value" + + assert response.span_id == "span_id_value" + + assert response.parent_span_id == "parent_span_id_value" + + assert response.span_kind == trace.Span.SpanKind.INTERNAL + + +def test_create_span_field_headers(): + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = trace.Span() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_span), "__call__") as call: + call.return_value = trace.Span() + + client.create_span(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_span_field_headers_async(): + client = TraceServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = trace.Span() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_span), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trace.Span()) + + await client.create_span(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TraceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TraceServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = TraceServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TraceServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TraceServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TraceServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.TraceServiceGrpcTransport,) + + +def test_trace_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.TraceServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_trace_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.trace_v2.services.trace_service.transports.TraceServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.TraceServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "batch_write_spans", + "create_span", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_trace_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.trace_v2.services.trace_service.transports.TraceServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.TraceServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ), + quota_project_id="octopus", + ) + + +def test_trace_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + TraceServiceClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ), + quota_project_id=None, + ) + + +def test_trace_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ), + quota_project_id="octopus", + ) + + +def test_trace_service_host_no_port(): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudtrace.googleapis.com" + ), + ) + assert client._transport._host == "cloudtrace.googleapis.com:443" + + +def test_trace_service_host_with_port(): + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudtrace.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudtrace.googleapis.com:8000" + + +def test_trace_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_trace_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.TraceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_trace_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_trace_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.TraceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_trace_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TraceServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_trace_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.TraceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/trace.append", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_span_path(): + project = "squid" + trace = "clam" + span = "whelk" + + expected = "projects/{project}/traces/{trace}/spans/{span}".format( + project=project, trace=trace, span=span, + ) + actual = TraceServiceClient.span_path(project, trace, span) + assert expected == actual + + +def test_parse_span_path(): + expected = { + "project": "octopus", + "trace": "oyster", + "span": "nudibranch", + } + path = TraceServiceClient.span_path(**expected) + + # Check that the path construction is reversible. + actual = TraceServiceClient.parse_span_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.TraceServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = TraceServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.TraceServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = TraceServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/v1/test_trace_service_client_v1.py b/tests/unit/gapic/v1/test_trace_service_client_v1.py deleted file mode 100644 index 873f7d77..00000000 --- a/tests/unit/gapic/v1/test_trace_service_client_v1.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import trace_v1 -from google.cloud.trace_v1.proto import trace_pb2 -from google.protobuf import empty_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestTraceServiceClient(object): - def test_patch_traces(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v1.TraceServiceClient() - - # Setup Request - project_id = "projectId-1969970175" - traces = {} - - client.patch_traces(project_id, traces) - - assert len(channel.requests) == 1 - expected_request = trace_pb2.PatchTracesRequest( - project_id=project_id, traces=traces - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_patch_traces_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v1.TraceServiceClient() - - # Setup request - project_id = "projectId-1969970175" - traces = {} - - with pytest.raises(CustomException): - client.patch_traces(project_id, traces) - - def test_list_traces(self): - # Setup Expected Response - next_page_token = "" - traces_element = {} - traces = [traces_element] - expected_response = {"next_page_token": next_page_token, "traces": traces} - expected_response = trace_pb2.ListTracesResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v1.TraceServiceClient() - - # Setup Request - project_id = "projectId-1969970175" - - paged_list_response = client.list_traces(project_id) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.traces[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = trace_pb2.ListTracesRequest(project_id=project_id) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_traces_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v1.TraceServiceClient() - - # Setup request - project_id = "projectId-1969970175" - - paged_list_response = client.list_traces(project_id) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_trace(self): - # Setup Expected Response - project_id_2 = "projectId2939242356" - trace_id_2 = "traceId2987826376" - expected_response = {"project_id": project_id_2, "trace_id": trace_id_2} - expected_response = trace_pb2.Trace(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v1.TraceServiceClient() - - # Setup Request - project_id = "projectId-1969970175" - trace_id = "traceId1270300245" - - response = client.get_trace(project_id, trace_id) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = trace_pb2.GetTraceRequest( - project_id=project_id, trace_id=trace_id - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_trace_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v1.TraceServiceClient() - - # Setup request - project_id = "projectId-1969970175" - trace_id = "traceId1270300245" - - with pytest.raises(CustomException): - client.get_trace(project_id, trace_id) diff --git a/tests/unit/gapic/v2/test_trace_service_client_v2.py b/tests/unit/gapic/v2/test_trace_service_client_v2.py deleted file mode 100644 index 8e213082..00000000 --- a/tests/unit/gapic/v2/test_trace_service_client_v2.py +++ /dev/null @@ -1,155 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import trace_v2 -from google.cloud.trace_v2.proto import trace_pb2 -from google.cloud.trace_v2.proto import tracing_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestTraceServiceClient(object): - def test_create_span(self): - # Setup Expected Response - name_2 = "name2-1052831874" - span_id_2 = "spanId2-643891741" - parent_span_id = "parentSpanId-1757797477" - expected_response = { - "name": name_2, - "span_id": span_id_2, - "parent_span_id": parent_span_id, - } - expected_response = trace_pb2.Span(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v2.TraceServiceClient() - - # Setup Request - name = client.span_path("[PROJECT]", "[TRACE]", "[SPAN]") - span_id = "spanId-2011840976" - display_name = {} - start_time = {} - end_time = {} - - response = client.create_span(name, span_id, display_name, start_time, end_time) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = trace_pb2.Span( - name=name, - span_id=span_id, - display_name=display_name, - start_time=start_time, - end_time=end_time, - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_span_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v2.TraceServiceClient() - - # Setup request - name = client.span_path("[PROJECT]", "[TRACE]", "[SPAN]") - span_id = "spanId-2011840976" - display_name = {} - start_time = {} - end_time = {} - - with pytest.raises(CustomException): - client.create_span(name, span_id, display_name, start_time, end_time) - - def test_batch_write_spans(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v2.TraceServiceClient() - - # Setup Request - name = client.project_path("[PROJECT]") - spans = [] - - client.batch_write_spans(name, spans) - - assert len(channel.requests) == 1 - expected_request = tracing_pb2.BatchWriteSpansRequest(name=name, spans=spans) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_write_spans_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = trace_v2.TraceServiceClient() - - # Setup request - name = client.project_path("[PROJECT]") - spans = [] - - with pytest.raises(CustomException): - client.batch_write_spans(name, spans) diff --git a/tests/unit/v1/test__gapic_v1.py b/tests/unit/v1/test__gapic_v1.py deleted file mode 100644 index bf9103e7..00000000 --- a/tests/unit/v1/test__gapic_v1.py +++ /dev/null @@ -1,247 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import datetime -import unittest - -import mock - - -class Test__TraceAPI(unittest.TestCase): - project = "PROJECT" - - @staticmethod - def _get_target_class(): - from google.cloud.trace.v1._gapic import _TraceAPI - - return _TraceAPI - - def _make_one(self, gapic_client=None, handwritten_client=None): - from google.cloud.trace_v1.gapic import trace_service_client - - if gapic_client is None: - gapic_client = mock.create_autospec(trace_service_client.TraceServiceClient) - if handwritten_client is None: - handwritten_client = mock.Mock() - api = self._get_target_class()(gapic_client, handwritten_client) - return api - - def test_constructor(self): - from google.cloud.trace_v1.gapic import trace_service_client - - gapic_client = mock.create_autospec(trace_service_client.TraceServiceClient) - api = self._make_one(gapic_client, mock.sentinel.client) - self.assertIs(api._gapic_api, gapic_client) - self.assertIs(api.client, mock.sentinel.client) - - def test_patch_traces(self): - from google.cloud.trace_v1.gapic import trace_service_client - from google.cloud.trace.v1._gapic import _traces_mapping_to_pb - - trace_id = "test_trace_id" - span_id = 1234 - span_name = "test_span_name" - start_time = datetime.datetime.utcnow() - end_time = datetime.datetime.utcnow() - traces = { - "traces": [ - { - "projectId": self.project, - "traceId": trace_id, - "spans": [ - { - "spanId": span_id, - "name": span_name, - "startTime": start_time.isoformat() + "Z", - "endTime": end_time.isoformat() + "Z", - } - ], - } - ] - } - traces_pb = _traces_mapping_to_pb(traces) - gapic_api = mock.create_autospec(trace_service_client.TraceServiceClient) - api = self._make_one(gapic_api, None) - - api.patch_traces(project_id=self.project, traces=traces) - - gapic_api.patch_traces.assert_called_once_with(self.project, traces_pb) - - def test_get_trace(self): - from google.cloud.trace_v1.gapic import trace_service_client - from google.cloud.trace_v1.proto.trace_pb2 import Trace - - trace_id = "test_trace_id" - trace_pb = Trace(project_id=self.project, trace_id=trace_id) - - gapic_api = mock.create_autospec(trace_service_client.TraceServiceClient) - gapic_api.get_trace.return_value = trace_pb - api = self._make_one(gapic_api, None) - - trace = api.get_trace(project_id=self.project, trace_id=trace_id) - - expected_trace = {"projectId": self.project, "traceId": trace_id} - self.assertEqual(trace, expected_trace) - - gapic_api.get_trace.assert_called_with(self.project, trace_id) - - def test_list_traces(self): - from google.api_core.page_iterator import GRPCIterator - from google.cloud.trace_v1.gapic import trace_service_client - from google.cloud.trace_v1.gapic.enums import ListTracesRequest as Enum - from google.cloud.trace.v1._gapic import _item_to_mapping - - page_size = 10 - view_type = Enum.ViewType.COMPLETE - page_token = "TOKEN" - gapic_api = mock.create_autospec(trace_service_client.TraceServiceClient) - response_iter = mock.create_autospec(GRPCIterator) - gapic_api.list_traces.return_value = response_iter - api = self._make_one(gapic_api) - - iterator = api.list_traces( - project_id=self.project, - view=view_type, - page_size=page_size, - page_token=page_token, - ) - - self.assertIs(iterator, response_iter) - self.assertIs(iterator.item_to_value, _item_to_mapping) - self.assertEqual(iterator.next_page_token, page_token) - - gapic_api.list_traces.assert_called_once_with( - project_id=self.project, - view=view_type, - page_size=page_size, - start_time=None, - end_time=None, - filter_=None, - order_by=None, - ) - - -class _TracePbBase(object): - project = u"PROJECT" - trace_id = u"test_trace_id" - span_id = 1234 - span_name = u"test_span_name" - start_time = "2017-06-24T00:12:50.369990Z" - end_time = "2017-06-24T00:13:39.633255Z" - start_seconds = 1498263170 - start_nanos = 369990000 - end_seconds = 1498263219 - end_nanos = 633255000 - - @classmethod - def _make_trace_pb(cls): - from google.cloud.trace_v1.proto.trace_pb2 import Trace - from google.cloud.trace_v1.proto.trace_pb2 import TraceSpan - from google.protobuf.timestamp_pb2 import Timestamp - - start_time_pb = Timestamp(seconds=cls.start_seconds, nanos=cls.start_nanos) - end_time_pb = Timestamp(seconds=cls.end_seconds, nanos=cls.end_nanos) - - span_pb = TraceSpan( - span_id=cls.span_id, - name=cls.span_name, - start_time=start_time_pb, - end_time=end_time_pb, - ) - - return Trace(project_id=cls.project, trace_id=cls.trace_id, spans=[span_pb]) - - @classmethod - def _expected_json(cls): - return { - "projectId": cls.project, - "traceId": cls.trace_id, - "spans": [ - { - "spanId": str(cls.span_id), - "name": cls.span_name, - "startTime": cls.start_time, - "endTime": cls.end_time, - } - ], - } - - -class Test__item_to_mapping(unittest.TestCase, _TracePbBase): - @staticmethod - def _call_fut(*args, **kwargs): - from google.cloud.trace.v1._gapic import _item_to_mapping - - return _item_to_mapping(*args, **kwargs) - - def test_registered_type(self): - iterator = object() - trace_pb = self._make_trace_pb() - - parsed_json = self._call_fut(iterator, trace_pb) - - expected_result = self._expected_json() - self.assertEqual(parsed_json, expected_result) - - -class Test__parse_trace_pb(unittest.TestCase, _TracePbBase): - @staticmethod - def _call_fut(*args, **kwargs): - from google.cloud.trace.v1._gapic import _parse_trace_pb - - return _parse_trace_pb(*args, **kwargs) - - def test_registered_type(self): - trace_pb = self._make_trace_pb() - - parsed_json = self._call_fut(trace_pb) - - expected_result = self._expected_json() - self.assertEqual(parsed_json, expected_result) - - @mock.patch("google.cloud.trace.v1._gapic.MessageToDict", side_effect=TypeError) - def test_unregistered_type(self, msg_to_dict_mock): - trace_pb = mock.Mock(spec=["HasField"]) - trace_pb.HasField.return_value = False - with self.assertRaises(TypeError): - self._call_fut(trace_pb) - - -class Test_make_trace_api(unittest.TestCase): - def _call_fut(self, client): - from google.cloud.trace.v1._gapic import make_trace_api - - return make_trace_api(client) - - def test_it(self): - from google.cloud.trace.v1._gapic import _TraceAPI - - client = mock.Mock(spec=["_credentials", "_client_info", "_client_options"]) - - patch_api = mock.patch( - "google.cloud.trace.v1._gapic.trace_service_client.TraceServiceClient" - ) - - with patch_api as patched: - trace_api = self._call_fut(client) - - patched.assert_called_once_with( - credentials=client._credentials, - client_info=client._client_info, - client_options=client._client_options, - ) - - self.assertIsInstance(trace_api, _TraceAPI) - self.assertIs(trace_api._gapic_api, patched.return_value) - self.assertIs(trace_api.client, client) diff --git a/tests/unit/v1/test_client_v1.py b/tests/unit/v1/test_client_v1.py deleted file mode 100644 index 9f50e868..00000000 --- a/tests/unit/v1/test_client_v1.py +++ /dev/null @@ -1,284 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import unittest - -import mock - - -def _make_credentials(): - import google.auth.credentials - - return mock.Mock(spec=google.auth.credentials.Credentials) - - -class TestClient(unittest.TestCase): - - project = "PROJECT" - - @staticmethod - def _get_target_class(): - from google.cloud.trace.v1.client import Client - - return Client - - def _make_one(self, *args, **kw): - return self._get_target_class()(*args, **kw) - - def test_constructor_defaults(self): - from google.api_core.gapic_v1.client_info import ClientInfo - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - self.assertEqual(client.project, self.project) - self.assertIsInstance(client._client_info, ClientInfo) - - def test_constructor_explicit(self): - credentials = _make_credentials() - client_info = mock.Mock() - client_options = mock.Mock() - client = self._make_one( - project=self.project, - credentials=credentials, - client_info=client_info, - client_options=client_options, - ) - self.assertEqual(client.project, self.project) - self.assertIs(client._client_info, client_info) - self.assertIs(client._client_options, client_options) - - def test_trace_api(self): - clients = [] - api_obj = object() - - def make_api(client_obj): - clients.append(client_obj) - return api_obj - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - - patch = mock.patch("google.cloud.trace.v1.client.make_trace_api", new=make_api) - - with patch: - api = client.trace_api - - self.assertIs(api, api_obj) - self.assertEqual(clients, [client]) - - def test_trace_api_existing(self): - """Check that the client caches _trace_api.""" - client = self._make_one(project=self.project, credentials=_make_credentials()) - client._trace_api = mock.sentinel.trace_api - self.assertIs(client.trace_api, mock.sentinel.trace_api) - - def test_patch_traces_default(self): - from google.cloud.trace.v1._gapic import _TraceAPI - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - traces = "fake_traces_for_test" - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.patch_traces = mock.Mock() - patch = mock.patch( - "google.cloud.trace.v1.client.make_trace_api", return_value=mock_trace_api - ) - - with patch: - client.patch_traces(traces=traces) - - mock_trace_api.patch_traces.assert_called_with( - project_id="PROJECT", traces="fake_traces_for_test" - ) - - def test_patch_traces_explicit(self): - from google.cloud.trace.v1._gapic import _TraceAPI - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - traces = "fake_traces_for_test" - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.patch_traces = mock.Mock() - patch = mock.patch( - "google.cloud.trace.v1.client.make_trace_api", return_value=mock_trace_api - ) - - with patch: - client.patch_traces(project_id=self.project, traces=traces) - - mock_trace_api.patch_traces.assert_called_with( - project_id="PROJECT", traces="fake_traces_for_test" - ) - - def test_get_trace_default(self): - from google.cloud.trace.v1._gapic import _TraceAPI - - def get_trace(trace_id, project_id=None, options=None): - _get_trace_called_with = (trace_id, project_id, options) - return _get_trace_called_with - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - trace_id = "5e6e73b4131303cb6f5c9dfbaf104e33" - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.get_trace = get_trace - patch = mock.patch( - "google.cloud.trace.v1.client.make_trace_api", return_value=mock_trace_api - ) - - with patch: - get_trace_called_with = client.get_trace(trace_id=trace_id) - - self.assertEqual(get_trace_called_with, (trace_id, self.project, None)) - - def test_get_trace_explicit(self): - from google.cloud.trace.v1._gapic import _TraceAPI - - def get_trace(trace_id, project_id=None, options=None): - _get_trace_called_with = (trace_id, project_id, options) - return _get_trace_called_with - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - trace_id = "5e6e73b4131303cb6f5c9dfbaf104e33" - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.get_trace = get_trace - patch = mock.patch( - "google.cloud.trace.v1.client.make_trace_api", return_value=mock_trace_api - ) - - with patch: - get_trace_called_with = client.get_trace( - trace_id=trace_id, project_id=self.project - ) - - self.assertEqual(get_trace_called_with, (trace_id, self.project, None)) - - def test_list_traces_default(self): - from google.cloud.trace.v1._gapic import _TraceAPI - - def list_traces( - project_id, - view=None, - page_size=None, - start_time=None, - end_time=None, - filter_=None, - order_by=None, - page_token=None, - ): - _list_traces_called_with = ( - project_id, - view, - page_size, - start_time, - end_time, - filter_, - order_by, - page_token, - ) - return _list_traces_called_with - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.list_traces = list_traces - patch = mock.patch( - "google.cloud.trace.v1.client.make_trace_api", return_value=mock_trace_api - ) - - with patch: - list_traces_called_with = client.list_traces() - - self.assertEqual( - list_traces_called_with, - (self.project, None, None, None, None, None, None, None), - ) - - def test_list_traces_explicit(self): - from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.trace_v1.gapic.enums import ListTracesRequest as Enum - from google.cloud.trace.v1._gapic import _TraceAPI - - from datetime import datetime - - def list_traces( - project_id, - view=None, - page_size=None, - start_time=None, - end_time=None, - filter_=None, - order_by=None, - page_token=None, - ): - _list_traces_called_with = ( - project_id, - view, - page_size, - start_time, - end_time, - filter_, - order_by, - page_token, - ) - return _list_traces_called_with - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.list_traces = list_traces - patch = mock.patch( - "google.cloud.trace.v1.client.make_trace_api", return_value=mock_trace_api - ) - - view = Enum.ViewType.COMPLETE - page_size = 10 - start_time = datetime.utcnow() - end_time = datetime.utcnow() - filter_ = "+span:span1" - order_by = "traceId" - page_token = "TOKEN" - - with patch: - list_traces_called_with = client.list_traces( - project_id=self.project, - view=view, - page_size=page_size, - start_time=start_time, - end_time=end_time, - filter_=filter_, - order_by=order_by, - page_token=page_token, - ) - - self.assertEqual( - list_traces_called_with, - ( - self.project, - view, - page_size, - _datetime_to_pb_timestamp(start_time), - _datetime_to_pb_timestamp(end_time), - filter_, - order_by, - page_token, - ), - ) diff --git a/tests/unit/v2/test__gapic_v2.py b/tests/unit/v2/test__gapic_v2.py deleted file mode 100644 index fd647240..00000000 --- a/tests/unit/v2/test__gapic_v2.py +++ /dev/null @@ -1,292 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import datetime -import unittest - -import mock - - -def _str_to_truncatablestr(str_to_convert): - result = {"value": str_to_convert, "truncated_byte_count": 0} - return result - - -class _Base(object): - from google.cloud.trace_v2.gapic import enums - - # Set the constants used for tests - project = "PROJECT" - trace_id = "c801e4119a064c659fe052d88f1d461b" - span_id = "1234123412341234" - parent_span_id = "1111000011110000" - span_name = "projects/{}/traces/{}/spans/{}".format(project, trace_id, span_id) - start_time = datetime.datetime.utcnow() - end_time = datetime.datetime.utcnow() - type = enums.Span.TimeEvent.MessageEvent.Type.SENT - display_name = "test display name" - - attributes = { - "attributeMap": { - "test_int_key": {"int_value": 123}, - "test_str_key": {"string_value": _str_to_truncatablestr("str_value")}, - "test_bool_key": {"bool_value": True}, - } - } - - st_function_name = "test function name" - st_origin_name = "test original name" - st_file_name = "test file name" - st_line_number = 12 - st_column_number = 2 - st_test_module = "test module" - st_build_id = "test build id" - st_source_version = "test source version" - stack_trace = { - "stack_frames": { - "frame": [ - { - "function_name": _str_to_truncatablestr(st_function_name), - "original_function_name": _str_to_truncatablestr(st_origin_name), - "file_name": _str_to_truncatablestr(st_file_name), - "line_number": st_line_number, - "column_number": st_column_number, - "load_module": { - "module": _str_to_truncatablestr(st_test_module), - "build_id": _str_to_truncatablestr(st_build_id), - }, - "source_version": _str_to_truncatablestr(st_source_version), - } - ], - "dropped_frames_count": 0, - }, - "stack_trace_hash_id": 1234, - } - - te_time = datetime.datetime.utcnow().isoformat() + "Z" - te_description = "test description" - time_events = { - "time_event": [ - { - "time": te_time, - "annotation": { - "description": _str_to_truncatablestr(te_description), - "attributes": attributes, - }, # TimeEvent can contain either annotation - # or message_event - } - ], - "dropped_annotations_count": 0, - "dropped_message_events_count": 0, - } - - link_span_id = "1111222211112222" - links = { - "link": [ - { - "trace_id": trace_id, - "span_id": link_span_id, - "type": type, - "attributes": attributes, - } - ], - "dropped_links_count": 0, - } - - status_code = 888 - status_message = "test status message" - status = {"code": status_code, "message": status_message, "details": []} - - same_process_as_parent_span = True - child_span_count = 0 - - def _make_one(self, *args, **kw): - return self._get_target_class()(*args, **kw) - - -class Test__TraceAPI(_Base, unittest.TestCase): - @staticmethod - def _get_target_class(): - from google.cloud.trace._gapic import _TraceAPI - - return _TraceAPI - - def test_constructor(self): - gapic_api = object() - client = object() - api = self._make_one(gapic_api, client) - self.assertIs(api._gapic_api, gapic_api) - self.assertIs(api.client, client) - - def test_batch_write_spans(self): - from google.cloud.trace_v2.gapic import trace_service_client - from google.cloud.trace._gapic import _dict_mapping_to_pb - - spans = { - "spans": [ - { - "name": self.span_name, - "span_id": self.span_id, - "parent_span_id": self.parent_span_id, - "display_name": _str_to_truncatablestr(self.display_name), - "start_time": self.start_time.isoformat() + "Z", - "end_time": self.end_time.isoformat() + "Z", - "attributes": self.attributes, - "stack_trace": self.stack_trace, - "time_events": self.time_events, - "links": self.links, - "status": self.status, - "same_process_as_parent_span": self.same_process_as_parent_span, - "child_span_count": self.child_span_count, - } - ] - } - - spans_pb_list = [_dict_mapping_to_pb(spans["spans"][0], "Span")] - project_name = "projects/{}".format(self.project) - - gapic_api = mock.Mock(spec=trace_service_client.TraceServiceClient) - api = self._make_one(gapic_api, None) - retry = mock.Mock() - timeout = mock.Mock() - api.batch_write_spans(project_name, spans, retry, timeout) - - gapic_api.batch_write_spans.assert_called_with( - name=project_name, spans=spans_pb_list, retry=retry, timeout=timeout - ) - - def test_create_span_default(self): - from google.cloud.trace_v2.gapic import trace_service_client - from google.cloud.trace._gapic import _dict_mapping_to_pb - from google.cloud._helpers import _datetime_to_pb_timestamp - - gapic_api = mock.Mock(spec=trace_service_client.TraceServiceClient) - api = self._make_one(gapic_api, None) - api.create_span( - name=self.span_name, - span_id=self.span_id, - display_name=_str_to_truncatablestr(self.display_name), - start_time=self.start_time, - end_time=self.end_time, - ) - - display_name_pb = _dict_mapping_to_pb( - _str_to_truncatablestr(self.display_name), "TruncatableString" - ) - start_time_pb = _datetime_to_pb_timestamp(self.start_time) - end_time_pb = _datetime_to_pb_timestamp(self.end_time) - - gapic_api.create_span.assert_called_with( - name=self.span_name, - span_id=self.span_id, - display_name=display_name_pb, - start_time=start_time_pb, - end_time=end_time_pb, - parent_span_id=None, - attributes=None, - stack_trace=None, - time_events=None, - links=None, - status=None, - same_process_as_parent_span=None, - child_span_count=None, - ) - - def test_create_span_explicit(self): - from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.trace._gapic import ( - _dict_mapping_to_pb, - _span_attrs_to_pb, - _status_mapping_to_pb, - _value_to_pb, - ) - from google.cloud.trace_v2.gapic import trace_service_client - - gapic_api = mock.Mock(spec=trace_service_client.TraceServiceClient) - api = self._make_one(gapic_api, None) - api.create_span( - name=self.span_name, - span_id=self.span_id, - display_name=_str_to_truncatablestr(self.display_name), - start_time=self.start_time, - end_time=self.end_time, - parent_span_id=self.parent_span_id, - attributes=self.attributes, - stack_trace=self.stack_trace, - time_events=self.time_events, - links=self.links, - status=self.status, - same_process_as_parent_span=self.same_process_as_parent_span, - child_span_count=self.child_span_count, - ) - - display_name_pb = _dict_mapping_to_pb( - _str_to_truncatablestr(self.display_name), "TruncatableString" - ) - start_time_pb = _datetime_to_pb_timestamp(self.start_time) - end_time_pb = _datetime_to_pb_timestamp(self.end_time) - attributes_pb = _span_attrs_to_pb(self.attributes, "Attributes") - stack_trace_pb = _dict_mapping_to_pb(self.stack_trace, "StackTrace") - time_events_pb = _span_attrs_to_pb(self.time_events, "TimeEvents") - links_pb = _span_attrs_to_pb(self.links, "Links") - status_pb = _status_mapping_to_pb(self.status) - same_process_as_parent_span_pb = _value_to_pb( - self.same_process_as_parent_span, "BoolValue" - ) - child_span_count_pb = _value_to_pb(self.child_span_count, "Int32Value") - - gapic_api.create_span.assert_called_with( - name=self.span_name, - span_id=self.span_id, - display_name=display_name_pb, - start_time=start_time_pb, - end_time=end_time_pb, - parent_span_id=self.parent_span_id, - attributes=attributes_pb, - stack_trace=stack_trace_pb, - time_events=time_events_pb, - links=links_pb, - status=status_pb, - same_process_as_parent_span=same_process_as_parent_span_pb, - child_span_count=child_span_count_pb, - ) - - -class Test_make_trace_api(unittest.TestCase): - def _call_fut(self, client): - from google.cloud.trace._gapic import make_trace_api - - return make_trace_api(client) - - def test_it(self): - from google.cloud.trace._gapic import _TraceAPI - - client = mock.Mock(spec=["_credentials", "_client_info", "_client_options"]) - - patch_api = mock.patch( - "google.cloud.trace._gapic.trace_service_client.TraceServiceClient" - ) - - with patch_api as patched: - trace_api = self._call_fut(client) - - patched.assert_called_once_with( - credentials=client._credentials, - client_info=client._client_info, - client_options=client._client_options, - ) - - self.assertIsInstance(trace_api, _TraceAPI) - self.assertIs(trace_api._gapic_api, patched.return_value) - self.assertIs(trace_api.client, client) diff --git a/tests/unit/v2/test_client_v2.py b/tests/unit/v2/test_client_v2.py deleted file mode 100644 index 4cd8a2a8..00000000 --- a/tests/unit/v2/test_client_v2.py +++ /dev/null @@ -1,162 +0,0 @@ -# Copyright 2017 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import unittest - -import mock - - -def _make_credentials(): - import google.auth.credentials - - return mock.Mock(spec=google.auth.credentials.Credentials) - - -class TestClient(unittest.TestCase): - - project = "PROJECT" - - @staticmethod - def _get_target_class(): - from google.cloud.trace.client import Client - - return Client - - def _make_one(self, *args, **kw): - return self._get_target_class()(*args, **kw) - - def test_constructor_defaults(self): - from google.api_core.gapic_v1.client_info import ClientInfo - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - self.assertEqual(client.project, self.project) - self.assertIsInstance(client._client_info, ClientInfo) - - def test_constructor_explicit(self): - credentials = _make_credentials() - client_info = mock.Mock() - client_options = mock.Mock() - client = self._make_one( - project=self.project, - credentials=credentials, - client_info=client_info, - client_options=client_options, - ) - self.assertEqual(client.project, self.project) - self.assertIs(client._client_options, client_options) - - def test_trace_api(self): - clients = [] - api_obj = object() - - def make_api(client_obj): - clients.append(client_obj) - return api_obj - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - - patch = mock.patch("google.cloud.trace.client.make_trace_api", new=make_api) - - with patch: - api = client.trace_api - - self.assertIs(api, api_obj) - self.assertEqual(clients, [client]) - - def test_trace_api_existing(self): - """Check that the client caches _trace_api.""" - client = self._make_one(project=self.project, credentials=_make_credentials()) - client._trace_api = mock.sentinel.trace_api - self.assertIs(client.trace_api, mock.sentinel.trace_api) - - def test_batch_write_spans(self): - from google.cloud.trace._gapic import _TraceAPI - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - name = "projects/{}".format(self.project) - spans = "fake_spans_for_test" - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.patch_traces = mock.Mock() - patch = mock.patch( - "google.cloud.trace.client.make_trace_api", return_value=mock_trace_api - ) - - with patch: - client.batch_write_spans(name=name, spans=spans) - - mock_trace_api.batch_write_spans.assert_called_with( - name=name, spans=spans, retry=None, timeout=None - ) - - def test_create_span(self): - from google.cloud.trace._gapic import _TraceAPI - - credentials = _make_credentials() - client = self._make_one(project=self.project, credentials=credentials) - name = "projects/{}".format(self.project) - span_id = "1111" - display_name = "test display name" - start_time = "test start time" - end_time = "test end time" - parent_span_id = "test parent span id" - attributes = "test attributes" - stack_trace = "test stack trace" - time_events = "test time events" - links = "test links" - status = "test status" - same_process_as_parent_span = "test same process as parent span" - child_span_count = "test child span count" - - mock_trace_api = mock.Mock(spec=_TraceAPI) - mock_trace_api.patch_traces = mock.Mock() - patch = mock.patch( - "google.cloud.trace.client.make_trace_api", return_value=mock_trace_api - ) - - with patch: - client.create_span( - name=name, - span_id=span_id, - display_name=display_name, - start_time=start_time, - end_time=end_time, - parent_span_id=parent_span_id, - attributes=attributes, - stack_trace=stack_trace, - time_events=time_events, - links=links, - status=status, - same_process_as_parent_span=same_process_as_parent_span, - child_span_count=child_span_count, - ) - - mock_trace_api.create_span.assert_called_with( - name=name, - span_id=span_id, - display_name=display_name, - start_time=start_time, - end_time=end_time, - parent_span_id=parent_span_id, - attributes=attributes, - stack_trace=stack_trace, - time_events=time_events, - links=links, - status=status, - same_process_as_parent_span=same_process_as_parent_span, - child_span_count=child_span_count, - )