From 86316d4b35906fd4330aa9a07fc95367d3c4577d Mon Sep 17 00:00:00 2001 From: Angela Li Date: Wed, 26 Jul 2017 13:51:56 -0700 Subject: [PATCH] Auto-generated trace library (GAPIC only) (#3512) --- docs/trace/apis.rst | 19 + docs/trace/conf.py | 311 +++++++ docs/trace/index.rst | 41 + docs/trace/starting.rst | 78 ++ nox.py | 2 +- trace/.coveragerc | 11 + trace/LICENSE | 201 +++++ trace/MANIFEST.in | 7 + trace/PUBLISHING.rst | 46 ++ trace/README.rst | 97 +++ trace/google/__init__.py | 1 + trace/google/cloud/__init__.py | 1 + trace/google/cloud/gapic/__init__.py | 1 + trace/google/cloud/gapic/trace/__init__.py | 1 + trace/google/cloud/gapic/trace/v1/__init__.py | 0 trace/google/cloud/gapic/trace/v1/enums.py | 53 ++ .../gapic/trace/v1/trace_service_client.py | 310 +++++++ .../trace/v1/trace_service_client_config.json | 43 + trace/google/cloud/proto/__init__.py | 1 + trace/google/cloud/proto/devtools/__init__.py | 1 + .../proto/devtools/cloudtrace/__init__.py | 1 + .../proto/devtools/cloudtrace/v1/__init__.py | 1 + .../proto/devtools/cloudtrace/v1/trace_pb2.py | 765 ++++++++++++++++++ .../devtools/cloudtrace/v1/trace_pb2_grpc.py | 93 +++ trace/google/cloud/trace.py | 24 + trace/google/cloud/trace/__init__.py | 18 + trace/google/cloud/trace/_gax.py | 213 +++++ trace/google/cloud/trace/client.py | 167 ++++ trace/google/cloud/trace_v1/__init__.py | 25 + trace/google/cloud/trace_v1/types.py | 28 + trace/nox.py | 79 ++ trace/setup.py | 44 + trace/tests/__init__.py | 13 + .../gapic/v1/test_trace_service_client_v1.py | 177 ++++ trace/tests/unit/test__gax.py | 429 ++++++++++ trace/tests/unit/test_client.py | 252 ++++++ 36 files changed, 3553 insertions(+), 1 deletion(-) create mode 100644 docs/trace/apis.rst create mode 100644 docs/trace/conf.py create mode 100644 docs/trace/index.rst create mode 100644 docs/trace/starting.rst create mode 100644 trace/.coveragerc create mode 100644 trace/LICENSE create mode 100644 trace/MANIFEST.in create mode 100644 trace/PUBLISHING.rst create mode 100644 trace/README.rst create mode 100644 trace/google/__init__.py create mode 100644 trace/google/cloud/__init__.py create mode 100644 trace/google/cloud/gapic/__init__.py create mode 100644 trace/google/cloud/gapic/trace/__init__.py create mode 100644 trace/google/cloud/gapic/trace/v1/__init__.py create mode 100644 trace/google/cloud/gapic/trace/v1/enums.py create mode 100644 trace/google/cloud/gapic/trace/v1/trace_service_client.py create mode 100644 trace/google/cloud/gapic/trace/v1/trace_service_client_config.json create mode 100644 trace/google/cloud/proto/__init__.py create mode 100644 trace/google/cloud/proto/devtools/__init__.py create mode 100644 trace/google/cloud/proto/devtools/cloudtrace/__init__.py create mode 100644 trace/google/cloud/proto/devtools/cloudtrace/v1/__init__.py create mode 100644 trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2.py create mode 100644 trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2_grpc.py create mode 100644 trace/google/cloud/trace.py create mode 100644 trace/google/cloud/trace/__init__.py create mode 100644 trace/google/cloud/trace/_gax.py create mode 100644 trace/google/cloud/trace/client.py create mode 100644 trace/google/cloud/trace_v1/__init__.py create mode 100644 trace/google/cloud/trace_v1/types.py create mode 100644 trace/nox.py create mode 100644 trace/setup.py create mode 100644 trace/tests/__init__.py create mode 100644 trace/tests/gapic/v1/test_trace_service_client_v1.py create mode 100644 trace/tests/unit/test__gax.py create mode 100644 trace/tests/unit/test_client.py diff --git a/docs/trace/apis.rst b/docs/trace/apis.rst new file mode 100644 index 000000000000..80a8d50c0c60 --- /dev/null +++ b/docs/trace/apis.rst @@ -0,0 +1,19 @@ +API Reference +============= + +APIs +---- + +.. autosummary:: + :toctree: + + google.cloud.gapic.trace.v1.trace_service_client + + +API types +~~~~~~~~~ + +.. autosummary:: + :toctree: + + google.cloud.gapic.trace.v1.enums diff --git a/docs/trace/conf.py b/docs/trace/conf.py new file mode 100644 index 000000000000..5eead079b01c --- /dev/null +++ b/docs/trace/conf.py @@ -0,0 +1,311 @@ +# -*- coding: utf-8 -*- +# +# google-cloud-trace documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath('..')) + +__version__ = '0.15.4' + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.autosummary', + 'sphinx.ext.intersphinx', + 'sphinx.ext.coverage', + 'sphinx.ext.napoleon', + 'sphinx.ext.viewcode', +] + +# autodoc/autosummary flags +autoclass_content = 'both' +autodoc_default_flags = ['members'] +autosummary_generate = True + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'google-cloud-trace' +copyright = u'2017, Google' +author = u'Google APIs' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = '.'.join(release.split('.')[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +# html_static_path = [] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +#html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +#html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +#html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'google-cloud-trace-doc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + #'preamble': '', + + # Latex figure (float) alignment + #'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'google-cloud-trace.tex', + u'google-cloud-trace Documentation', author, 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [(master_doc, 'google-cloud-trace', + u'google-cloud-trace Documentation', [author], 1)] + +# If true, show URL addresses after external links. +#man_show_urls = False + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'google-cloud-trace', + u'google-cloud-trace Documentation', author, + 'google-cloud-trace', + 'GAPIC library for the {metadata.shortName} v1 service', 'APIs'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + 'python': ('http://python.readthedocs.org/en/latest/', None), + 'gax': ('https://gax-python.readthedocs.org/en/latest/', None), +} + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/docs/trace/index.rst b/docs/trace/index.rst new file mode 100644 index 000000000000..08044709bcc6 --- /dev/null +++ b/docs/trace/index.rst @@ -0,0 +1,41 @@ +.. gapic-google-cloud-trace-v1 sphinx documentation master file + + +GAPIC library for the Stackdriver Trace API +============================================================================================================= + +This is the API documentation for ``gapic-google-cloud-trace-v1``. + +gapic-google-cloud-trace-v1 uses google-gax_ (Google API extensions) to provide an +easy-to-use client library for the `Stackdriver Trace API`_ (v1) defined in the googleapis_ git repository + + +.. _`google-gax`: https://github.com/googleapis/gax-python +.. _`googleapis`: https://github.com/googleapis/googleapis/tree/master/google/devtools/cloudtrace/v1 +.. _`Stackdriver Trace API`: https://developers.google.com/apis-explorer/?hl=en_US#p/cloudtrace/v1/ + + +APIs +---- + +.. autosummary:: + + google.cloud.gapic.trace.v1.trace_service_client + + +Contents +-------- + +.. toctree:: + + self + starting + apis + + +Indices and tables +------------------ + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/trace/starting.rst b/docs/trace/starting.rst new file mode 100644 index 000000000000..245fcfd68a87 --- /dev/null +++ b/docs/trace/starting.rst @@ -0,0 +1,78 @@ +Getting started +=============== + +gapic-google-cloud-trace-v1 will allow you to connect to the `Stackdriver Trace API`_ and access all its methods. In order to achieve this, you need to set up authentication as well as install the library locally. + +.. _`Stackdriver Trace API`: https://developers.google.com/apis-explorer/?hl=en_US#p/cloudtrace/v1/ + + +Installation +------------ + + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +~~~~~~~~~~ + +.. code-block:: console + + pip install virtualenv + virtualenv + source /bin/activate + /bin/pip install gapic-google-cloud-trace-v1 + +Windows +~~~~~~~ + +.. code-block:: console + + pip install virtualenv + virtualenv + \Scripts\activate + \Scripts\pip.exe install gapic-google-cloud-trace-v1 + + +Using the API +------------- + + +Authentication +~~~~~~~~~~~~~~ + +To authenticate all your API calls, first install and setup the `Google Cloud SDK`_. +Once done, you can then run the following command in your terminal: + +.. code-block:: console + + $ gcloud beta auth application-default login + +or + +.. code-block:: console + + $ gcloud auth login + +Please see `gcloud beta auth application-default login`_ document for the difference between these commands. + +.. _Google Cloud SDK: https://cloud.google.com/sdk/ +.. _gcloud beta auth application-default login: https://cloud.google.com/sdk/gcloud/reference/beta/auth/application-default/login +.. code-block:: console + +At this point you are all set to continue. + + +Examples +~~~~~~~~ + +To see example usage, please read through the :doc:`API reference `. The +documentation for each API method includes simple examples. diff --git a/nox.py b/nox.py index 3d283c821bdc..25db4c616c4f 100644 --- a/nox.py +++ b/nox.py @@ -34,7 +34,7 @@ def docs(session): 'core/', 'bigquery/', 'bigtable/', 'datastore/', 'dns/', 'language/', 'logging/', 'error_reporting/', 'monitoring/', 'pubsub/', 'resource_manager/', 'runtimeconfig/', 'spanner/', 'speech/', - 'storage/', 'translate/', 'vision/', + 'storage/', 'trace/', 'translate/', 'vision/', ) session.install('-e', '.') diff --git a/trace/.coveragerc b/trace/.coveragerc new file mode 100644 index 000000000000..a54b99aa14b7 --- /dev/null +++ b/trace/.coveragerc @@ -0,0 +1,11 @@ +[run] +branch = True + +[report] +fail_under = 100 +show_missing = True +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/trace/LICENSE b/trace/LICENSE new file mode 100644 index 000000000000..724a8807144b --- /dev/null +++ b/trace/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/trace/MANIFEST.in b/trace/MANIFEST.in new file mode 100644 index 000000000000..8a2c2aa5ab99 --- /dev/null +++ b/trace/MANIFEST.in @@ -0,0 +1,7 @@ +include README.rst LICENSE +recursive-include tests * +global-include google *.json *.proto +graft google +global-exclude *.py[co] +global-exclude __pycache__ +prune .tox diff --git a/trace/PUBLISHING.rst b/trace/PUBLISHING.rst new file mode 100644 index 000000000000..a6d81225248b --- /dev/null +++ b/trace/PUBLISHING.rst @@ -0,0 +1,46 @@ +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/trace/README.rst b/trace/README.rst new file mode 100644 index 000000000000..39178ee440fc --- /dev/null +++ b/trace/README.rst @@ -0,0 +1,97 @@ +Python Client for Stackdriver Trace API (`Alpha`_) +================================================================================================== + +Idiomatic Python client for `Stackdriver Trace API`_ + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. _Alpha: https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/README.rst +.. _Stackdriver Trace API: https://cloud.google.com/trace +.. _Client Library Documentation: https://googlecloudplatform.github.io/google-cloud-python/stable/trace-usage +.. _Product Documentation: https://cloud.google.com/trace + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable the monitoring api.`_ +3. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable the trace api.: https://cloud.google.com/trace +.. _Setup Authentication.: https://googlecloudplatform.github.io/google-cloud-python/stable/google-cloud-auth + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + pip install virtualenv + virtualenv + source /bin/activate + /bin/pip install gapic-google-cloud-trace-v1 + + +Windows +^^^^^^^ + +.. code-block:: console + + pip install virtualenv + virtualenv + \Scripts\activate + \Scripts\pip.exe install gapic-google-cloud-trace-v1 + +Preview +~~~~~~~ + +TraceServiceClient +^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: py + + from google.cloud.gapic.trace.v1 import trace_service_client + from google.gax import CallOptions, INITIAL_PAGE + client = trace_service_client.TraceServiceClient() + project_id = '' + + # Iterate over all results + for element in client.list_traces(project_id): + # process element + pass + + # Or iterate over results one page at a time + for page in client.list_traces(project_id, options=CallOptions(page_token=INITIAL_PAGE)): + for element in page: + # process element + pass + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Stackdriver Trace API + API to see other available methods on the client. +- Read the `Stackdriver Trace API Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `repository’s main README`_ to see the full list of Cloud + APIs that we cover. + +.. _Stackdriver Trace API Product documentation: https://cloud.google.com/trace +.. _repository’s main README: https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/README.rst \ No newline at end of file diff --git a/trace/google/__init__.py b/trace/google/__init__.py new file mode 100644 index 000000000000..de40ea7ca058 --- /dev/null +++ b/trace/google/__init__.py @@ -0,0 +1 @@ +__import__('pkg_resources').declare_namespace(__name__) diff --git a/trace/google/cloud/__init__.py b/trace/google/cloud/__init__.py new file mode 100644 index 000000000000..de40ea7ca058 --- /dev/null +++ b/trace/google/cloud/__init__.py @@ -0,0 +1 @@ +__import__('pkg_resources').declare_namespace(__name__) diff --git a/trace/google/cloud/gapic/__init__.py b/trace/google/cloud/gapic/__init__.py new file mode 100644 index 000000000000..de40ea7ca058 --- /dev/null +++ b/trace/google/cloud/gapic/__init__.py @@ -0,0 +1 @@ +__import__('pkg_resources').declare_namespace(__name__) diff --git a/trace/google/cloud/gapic/trace/__init__.py b/trace/google/cloud/gapic/trace/__init__.py new file mode 100644 index 000000000000..de40ea7ca058 --- /dev/null +++ b/trace/google/cloud/gapic/trace/__init__.py @@ -0,0 +1 @@ +__import__('pkg_resources').declare_namespace(__name__) diff --git a/trace/google/cloud/gapic/trace/v1/__init__.py b/trace/google/cloud/gapic/trace/v1/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/trace/google/cloud/gapic/trace/v1/enums.py b/trace/google/cloud/gapic/trace/v1/enums.py new file mode 100644 index 000000000000..c6cc48fb471a --- /dev/null +++ b/trace/google/cloud/gapic/trace/v1/enums.py @@ -0,0 +1,53 @@ +# Copyright 2016 Google Inc. All rights reserved. +# +# 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. +"""Wrappers for protocol buffer enum types.""" + + +class TraceSpan(object): + class SpanKind(object): + """ + 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 + + +class ListTracesRequest(object): + class ViewType(object): + """ + 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 diff --git a/trace/google/cloud/gapic/trace/v1/trace_service_client.py b/trace/google/cloud/gapic/trace/v1/trace_service_client.py new file mode 100644 index 000000000000..22ef0eb1aec1 --- /dev/null +++ b/trace/google/cloud/gapic/trace/v1/trace_service_client.py @@ -0,0 +1,310 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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. +# +# EDITING INSTRUCTIONS +# This file was generated from the file +# https://github.com/google/googleapis/blob/master/google/devtools/cloudtrace/v1/trace.proto, +# and updates to that file get reflected here through a refresh process. +# For the short term, the refresh process will only be runnable by Google engineers. +# +# The only allowed edits are to method and file documentation. A 3-way +# merge preserves those additions if the generated source changes. +"""Accesses the google.devtools.cloudtrace.v1 TraceService API.""" + +import collections +import json +import os +import pkg_resources +import platform + +from google.gax import api_callable +from google.gax import config +from google.gax import path_template +import google.gax + +from google.cloud.gapic.trace.v1 import enums +from google.cloud.proto.devtools.cloudtrace.v1 import trace_pb2 +from google.protobuf import timestamp_pb2 + +_PageDesc = google.gax.PageDescriptor + + +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' + """The default address of the service.""" + + DEFAULT_SERVICE_PORT = 443 + """The default port of the service.""" + + _PAGE_DESCRIPTORS = { + 'list_traces': _PageDesc('page_token', 'next_page_token', 'traces') + } + + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _ALL_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, + service_path=SERVICE_ADDRESS, + port=DEFAULT_SERVICE_PORT, + channel=None, + credentials=None, + ssl_credentials=None, + scopes=None, + client_config=None, + app_name=None, + app_version='', + lib_name=None, + lib_version='', + metrics_headers=()): + """Constructor. + + Args: + service_path (string): The domain name of the API remote host. + port (int): The port on which to connect to the remote host. + channel (:class:`grpc.Channel`): A ``Channel`` instance through + which to make calls. + credentials (object): The authorization credentials to attach to + requests. These credentials identify this application to the + service. + ssl_credentials (:class:`grpc.ChannelCredentials`): A + ``ChannelCredentials`` instance for use with an SSL-enabled + channel. + scopes (list[string]): A list of OAuth2 scopes to attach to requests. + client_config (dict): + A dictionary for call options for each method. See + :func:`google.gax.construct_settings` for the structure of + this data. Falls back to the default config if not specified + or the specified config is missing data points. + app_name (string): The name of the application calling + the service. Recommended for analytics purposes. + app_version (string): The version of the application calling + the service. Recommended for analytics purposes. + lib_name (string): The API library software used for calling + the service. (Unless you are writing an API client itself, + leave this as default.) + lib_version (string): The API library software version used + for calling the service. (Unless you are writing an API client + itself, leave this as default.) + metrics_headers (dict): A dictionary of values for tracking + client library metrics. Ultimately serializes to a string + (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be + considered private. + + Returns: + A TraceServiceClient object. + """ + # Unless the calling application specifically requested + # OAuth scopes, request everything. + if scopes is None: + scopes = self._ALL_SCOPES + + # Initialize an empty client config, if none is set. + if client_config is None: + client_config = {} + + # Initialize metrics_headers as an ordered dictionary + # (cuts down on cardinality of the resulting string slightly). + metrics_headers = collections.OrderedDict(metrics_headers) + metrics_headers['gl-python'] = platform.python_version() + + # The library may or may not be set, depending on what is + # calling this client. Newer client libraries set the library name + # and version. + if lib_name: + metrics_headers[lib_name] = lib_version + + # Finally, track the GAPIC package version. + metrics_headers['gapic'] = pkg_resources.get_distribution( + 'google-cloud-trace', ).version + + # Load the configuration defaults. + default_client_config = json.loads( + pkg_resources.resource_string( + __name__, 'trace_service_client_config.json').decode()) + defaults = api_callable.construct_settings( + 'google.devtools.cloudtrace.v1.TraceService', + default_client_config, + client_config, + config.STATUS_CODE_NAMES, + metrics_headers=metrics_headers, + page_descriptors=self._PAGE_DESCRIPTORS, ) + self.trace_service_stub = config.create_stub( + trace_pb2.TraceServiceStub, + channel=channel, + service_path=service_path, + service_port=port, + credentials=credentials, + scopes=scopes, + ssl_credentials=ssl_credentials) + + self._patch_traces = api_callable.create_api_call( + self.trace_service_stub.PatchTraces, + settings=defaults['patch_traces']) + self._get_trace = api_callable.create_api_call( + self.trace_service_stub.GetTrace, settings=defaults['get_trace']) + self._list_traces = api_callable.create_api_call( + self.trace_service_stub.ListTraces, + settings=defaults['list_traces']) + + # Service calls + def patch_traces(self, project_id, traces, options=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.gapic.trace.v1 import trace_service_client + >>> from google.cloud.proto.devtools.cloudtrace.v1 import trace_pb2 + >>> client = trace_service_client.TraceServiceClient() + >>> project_id = '' + >>> traces = trace_pb2.Traces() + >>> client.patch_traces(project_id, traces) + + Args: + project_id (string): ID of the Cloud project where the trace data is stored. + traces (:class:`google.cloud.proto.devtools.cloudtrace.v1.trace_pb2.Traces`): The body of the message. + options (:class:`google.gax.CallOptions`): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + # Create the request object. + request = trace_pb2.PatchTracesRequest( + project_id=project_id, traces=traces) + self._patch_traces(request, options) + + def get_trace(self, project_id, trace_id, options=None): + """ + Gets a single trace by its ID. + + Example: + >>> from google.cloud.gapic.trace.v1 import trace_service_client + >>> client = trace_service_client.TraceServiceClient() + >>> project_id = '' + >>> trace_id = '' + >>> response = client.get_trace(project_id, trace_id) + + Args: + project_id (string): ID of the Cloud project where the trace data is stored. + trace_id (string): ID of the trace to return. + options (:class:`google.gax.CallOptions`): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`google.cloud.proto.devtools.cloudtrace.v1.trace_pb2.Trace` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + # Create the request object. + request = trace_pb2.GetTraceRequest( + project_id=project_id, trace_id=trace_id) + return self._get_trace(request, options) + + def list_traces(self, + project_id, + view=None, + page_size=None, + start_time=None, + end_time=None, + filter_=None, + order_by=None, + options=None): + """ + Returns of a list of traces that match the specified filter conditions. + + Example: + >>> from google.cloud.gapic.trace.v1 import trace_service_client + >>> from google.gax import CallOptions, INITIAL_PAGE + >>> client = trace_service_client.TraceServiceClient() + >>> project_id = '' + >>> + >>> # Iterate over all results + >>> for element in client.list_traces(project_id): + >>> # process element + >>> pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_traces(project_id, options=CallOptions(page_token=INITIAL_PAGE)): + >>> for element in page: + >>> # process element + >>> pass + + Args: + project_id (string): ID of the Cloud project where the trace data is stored. + view (enum :class:`google.cloud.gapic.trace.v1.enums.ListTracesRequest.ViewType`): Type of data returned for traces in the list. Optional. Default is + ``MINIMAL``. + page_size (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. Optional. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): End of the time interval (inclusive) during which the trace data was + collected from the application. + end_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): Start of the time interval (inclusive) during which the trace data was + collected from the application. + filter_ (string): An optional filter for the request. + order_by (string): Field used to sort the returned traces. Optional. + 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. + options (:class:`google.gax.CallOptions`): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`google.gax.PageIterator` instance. By default, this + is an iterable of :class:`google.cloud.proto.devtools.cloudtrace.v1.trace_pb2.Trace` instances. + This object can also be configured to iterate over the pages + of the response through the `CallOptions` parameter. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + # Create the request object. + 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) + return self._list_traces(request, options) diff --git a/trace/google/cloud/gapic/trace/v1/trace_service_client_config.json b/trace/google/cloud/gapic/trace/v1/trace_service_client_config.json new file mode 100644 index 000000000000..5e826c186b13 --- /dev/null +++ b/trace/google/cloud/gapic/trace/v1/trace_service_client_config.json @@ -0,0 +1,43 @@ +{ + "interfaces": { + "google.devtools.cloudtrace.v1.TraceService": { + "retry_codes": { + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "non_idempotent": [ + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.2, + "max_retry_delay_millis": 1000, + "initial_rpc_timeout_millis": 20000, + "rpc_timeout_multiplier": 1.5, + "max_rpc_timeout_millis": 30000, + "total_timeout_millis": 45000 + } + }, + "methods": { + "PatchTraces": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "GetTrace": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListTraces": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/trace/google/cloud/proto/__init__.py b/trace/google/cloud/proto/__init__.py new file mode 100644 index 000000000000..de40ea7ca058 --- /dev/null +++ b/trace/google/cloud/proto/__init__.py @@ -0,0 +1 @@ +__import__('pkg_resources').declare_namespace(__name__) diff --git a/trace/google/cloud/proto/devtools/__init__.py b/trace/google/cloud/proto/devtools/__init__.py new file mode 100644 index 000000000000..de40ea7ca058 --- /dev/null +++ b/trace/google/cloud/proto/devtools/__init__.py @@ -0,0 +1 @@ +__import__('pkg_resources').declare_namespace(__name__) diff --git a/trace/google/cloud/proto/devtools/cloudtrace/__init__.py b/trace/google/cloud/proto/devtools/cloudtrace/__init__.py new file mode 100644 index 000000000000..de40ea7ca058 --- /dev/null +++ b/trace/google/cloud/proto/devtools/cloudtrace/__init__.py @@ -0,0 +1 @@ +__import__('pkg_resources').declare_namespace(__name__) diff --git a/trace/google/cloud/proto/devtools/cloudtrace/v1/__init__.py b/trace/google/cloud/proto/devtools/cloudtrace/v1/__init__.py new file mode 100644 index 000000000000..8b137891791f --- /dev/null +++ b/trace/google/cloud/proto/devtools/cloudtrace/v1/__init__.py @@ -0,0 +1 @@ + diff --git a/trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2.py b/trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2.py new file mode 100644 index 000000000000..389893c0d9fd --- /dev/null +++ b/trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2.py @@ -0,0 +1,765 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/proto/devtools/cloudtrace/v1/trace.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +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 +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__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/proto/devtools/cloudtrace/v1/trace.proto', + package='google.devtools.cloudtrace.v1', + syntax='proto3', + serialized_pb=_b('\n5google/cloud/proto/devtools/cloudtrace/v1/trace.proto\x12\x1dgoogle.devtools.cloudtrace.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.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\"\x9d\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\x16\n\x0eparent_span_id\x18\x06 \x01(\x06\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\"\xe7\x02\n\x11ListTracesRequest\x12\x12\n\nproject_id\x18\x01 \x01(\t\x12G\n\x04view\x18\x02 \x01(\x0e\x32\x39.google.devtools.cloudtrace.v1.ListTracesRequest.ViewType\x12\x11\n\tpage_size\x18\x03 \x01(\x05\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\x0e\n\x06\x66ilter\x18\x07 \x01(\t\x12\x10\n\x08order_by\x18\x08 \x01(\t\"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\"7\n\x0fGetTraceRequest\x12\x12\n\nproject_id\x18\x01 \x01(\t\x12\x10\n\x08trace_id\x18\x02 \x01(\t\"_\n\x12PatchTracesRequest\x12\x12\n\nproject_id\x18\x01 \x01(\t\x12\x35\n\x06traces\x18\x02 \x01(\x0b\x32%.google.devtools.cloudtrace.v1.Traces2\xd1\x03\n\x0cTraceService\x12\x9b\x01\n\nListTraces\x12\x30.google.devtools.cloudtrace.v1.ListTracesRequest\x1a\x31.google.devtools.cloudtrace.v1.ListTracesResponse\"(\x82\xd3\xe4\x93\x02\"\x12 /v1/projects/{project_id}/traces\x12\x95\x01\n\x08GetTrace\x12..google.devtools.cloudtrace.v1.GetTraceRequest\x1a$.google.devtools.cloudtrace.v1.Trace\"3\x82\xd3\xe4\x93\x02-\x12+/v1/projects/{project_id}/traces/{trace_id}\x12\x8a\x01\n\x0bPatchTraces\x12\x31.google.devtools.cloudtrace.v1.PatchTracesRequest\x1a\x16.google.protobuf.Empty\"0\x82\xd3\xe4\x93\x02*2 /v1/projects/{project_id}/traces:\x06tracesB\x92\x01\n!com.google.devtools.cloudtrace.v1B\nTraceProtoP\x01ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v1;cloudtrace\xaa\x02\x15Google.Cloud.Trace.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_TRACESPAN_SPANKIND = _descriptor.EnumDescriptor( + name='SpanKind', + full_name='google.devtools.cloudtrace.v1.TraceSpan.SpanKind', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='SPAN_KIND_UNSPECIFIED', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='RPC_SERVER', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='RPC_CLIENT', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=693, + serialized_end=762, +) +_sym_db.RegisterEnumDescriptor(_TRACESPAN_SPANKIND) + +_LISTTRACESREQUEST_VIEWTYPE = _descriptor.EnumDescriptor( + name='ViewType', + full_name='google.devtools.cloudtrace.v1.ListTracesRequest.ViewType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='VIEW_TYPE_UNSPECIFIED', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='MINIMAL', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='ROOTSPAN', index=2, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='COMPLETE', index=3, number=3, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1046, + serialized_end=1124, +) +_sym_db.RegisterEnumDescriptor(_LISTTRACESREQUEST_VIEWTYPE) + + +_TRACE = _descriptor.Descriptor( + name='Trace', + full_name='google.devtools.cloudtrace.v1.Trace', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + _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, + options=None), + _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, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=180, + serialized_end=282, +) + + +_TRACES = _descriptor.Descriptor( + name='Traces', + full_name='google.devtools.cloudtrace.v1.Traces', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=284, + serialized_end=346, +) + + +_TRACESPAN_LABELSENTRY = _descriptor.Descriptor( + name='LabelsEntry', + full_name='google.devtools.cloudtrace.v1.TraceSpan.LabelsEntry', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + _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, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')), + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=646, + serialized_end=691, +) + +_TRACESPAN = _descriptor.Descriptor( + name='TraceSpan', + full_name='google.devtools.cloudtrace.v1.TraceSpan', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + ], + extensions=[ + ], + nested_types=[_TRACESPAN_LABELSENTRY, ], + enum_types=[ + _TRACESPAN_SPANKIND, + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=349, + serialized_end=762, +) + + +_LISTTRACESREQUEST = _descriptor.Descriptor( + name='ListTracesRequest', + full_name='google.devtools.cloudtrace.v1.ListTracesRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + _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, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _LISTTRACESREQUEST_VIEWTYPE, + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=765, + serialized_end=1124, +) + + +_LISTTRACESRESPONSE = _descriptor.Descriptor( + name='ListTracesResponse', + full_name='google.devtools.cloudtrace.v1.ListTracesResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + _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, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1126, + serialized_end=1225, +) + + +_GETTRACEREQUEST = _descriptor.Descriptor( + name='GetTraceRequest', + full_name='google.devtools.cloudtrace.v1.GetTraceRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + _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, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1227, + serialized_end=1282, +) + + +_PATCHTRACESREQUEST = _descriptor.Descriptor( + name='PatchTracesRequest', + full_name='google.devtools.cloudtrace.v1.PatchTracesRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + 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, + options=None), + _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, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1284, + serialized_end=1379, +) + +_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 + +Trace = _reflection.GeneratedProtocolMessageType('Trace', (_message.Message,), dict( + DESCRIPTOR = _TRACE, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.Trace) + )) +_sym_db.RegisterMessage(Trace) + +Traces = _reflection.GeneratedProtocolMessageType('Traces', (_message.Message,), dict( + DESCRIPTOR = _TRACES, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.Traces) + )) +_sym_db.RegisterMessage(Traces) + +TraceSpan = _reflection.GeneratedProtocolMessageType('TraceSpan', (_message.Message,), dict( + + LabelsEntry = _reflection.GeneratedProtocolMessageType('LabelsEntry', (_message.Message,), dict( + DESCRIPTOR = _TRACESPAN_LABELSENTRY, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.TraceSpan.LabelsEntry) + )) + , + DESCRIPTOR = _TRACESPAN, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@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,), dict( + DESCRIPTOR = _LISTTRACESREQUEST, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.ListTracesRequest) + )) +_sym_db.RegisterMessage(ListTracesRequest) + +ListTracesResponse = _reflection.GeneratedProtocolMessageType('ListTracesResponse', (_message.Message,), dict( + DESCRIPTOR = _LISTTRACESRESPONSE, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.ListTracesResponse) + )) +_sym_db.RegisterMessage(ListTracesResponse) + +GetTraceRequest = _reflection.GeneratedProtocolMessageType('GetTraceRequest', (_message.Message,), dict( + DESCRIPTOR = _GETTRACEREQUEST, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.GetTraceRequest) + )) +_sym_db.RegisterMessage(GetTraceRequest) + +PatchTracesRequest = _reflection.GeneratedProtocolMessageType('PatchTracesRequest', (_message.Message,), dict( + DESCRIPTOR = _PATCHTRACESREQUEST, + __module__ = 'google.cloud.proto.devtools.cloudtrace.v1.trace_pb2' + # @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.PatchTracesRequest) + )) +_sym_db.RegisterMessage(PatchTracesRequest) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n!com.google.devtools.cloudtrace.v1B\nTraceProtoP\001ZGgoogle.golang.org/genproto/googleapis/devtools/cloudtrace/v1;cloudtrace\252\002\025Google.Cloud.Trace.V1')) +_TRACESPAN_LABELSENTRY.has_options = True +_TRACESPAN_LABELSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities + + + 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=ListTracesRequest.SerializeToString, + response_deserializer=ListTracesResponse.FromString, + ) + self.GetTrace = channel.unary_unary( + '/google.devtools.cloudtrace.v1.TraceService/GetTrace', + request_serializer=GetTraceRequest.SerializeToString, + response_deserializer=Trace.FromString, + ) + self.PatchTraces = channel.unary_unary( + '/google.devtools.cloudtrace.v1.TraceService/PatchTraces', + request_serializer=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=ListTracesRequest.FromString, + response_serializer=ListTracesResponse.SerializeToString, + ), + 'GetTrace': grpc.unary_unary_rpc_method_handler( + servicer.GetTrace, + request_deserializer=GetTraceRequest.FromString, + response_serializer=Trace.SerializeToString, + ), + 'PatchTraces': grpc.unary_unary_rpc_method_handler( + servicer.PatchTraces, + request_deserializer=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,)) + + + class BetaTraceServiceServicer(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """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.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetTrace(self, request, context): + """Gets a single trace by its ID. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + 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.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + + + class BetaTraceServiceStub(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """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, timeout, metadata=None, with_call=False, protocol_options=None): + """Returns of a list of traces that match the specified filter conditions. + """ + raise NotImplementedError() + ListTraces.future = None + def GetTrace(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Gets a single trace by its ID. + """ + raise NotImplementedError() + GetTrace.future = None + def PatchTraces(self, request, timeout, metadata=None, with_call=False, protocol_options=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. + """ + raise NotImplementedError() + PatchTraces.future = None + + + def beta_create_TraceService_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_deserializers = { + ('google.devtools.cloudtrace.v1.TraceService', 'GetTrace'): GetTraceRequest.FromString, + ('google.devtools.cloudtrace.v1.TraceService', 'ListTraces'): ListTracesRequest.FromString, + ('google.devtools.cloudtrace.v1.TraceService', 'PatchTraces'): PatchTracesRequest.FromString, + } + response_serializers = { + ('google.devtools.cloudtrace.v1.TraceService', 'GetTrace'): Trace.SerializeToString, + ('google.devtools.cloudtrace.v1.TraceService', 'ListTraces'): ListTracesResponse.SerializeToString, + ('google.devtools.cloudtrace.v1.TraceService', 'PatchTraces'): google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + } + method_implementations = { + ('google.devtools.cloudtrace.v1.TraceService', 'GetTrace'): face_utilities.unary_unary_inline(servicer.GetTrace), + ('google.devtools.cloudtrace.v1.TraceService', 'ListTraces'): face_utilities.unary_unary_inline(servicer.ListTraces), + ('google.devtools.cloudtrace.v1.TraceService', 'PatchTraces'): face_utilities.unary_unary_inline(servicer.PatchTraces), + } + server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) + return beta_implementations.server(method_implementations, options=server_options) + + + def beta_create_TraceService_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_serializers = { + ('google.devtools.cloudtrace.v1.TraceService', 'GetTrace'): GetTraceRequest.SerializeToString, + ('google.devtools.cloudtrace.v1.TraceService', 'ListTraces'): ListTracesRequest.SerializeToString, + ('google.devtools.cloudtrace.v1.TraceService', 'PatchTraces'): PatchTracesRequest.SerializeToString, + } + response_deserializers = { + ('google.devtools.cloudtrace.v1.TraceService', 'GetTrace'): Trace.FromString, + ('google.devtools.cloudtrace.v1.TraceService', 'ListTraces'): ListTracesResponse.FromString, + ('google.devtools.cloudtrace.v1.TraceService', 'PatchTraces'): google_dot_protobuf_dot_empty__pb2.Empty.FromString, + } + cardinalities = { + 'GetTrace': cardinality.Cardinality.UNARY_UNARY, + 'ListTraces': cardinality.Cardinality.UNARY_UNARY, + 'PatchTraces': cardinality.Cardinality.UNARY_UNARY, + } + stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) + return beta_implementations.dynamic_stub(channel, 'google.devtools.cloudtrace.v1.TraceService', cardinalities, options=stub_options) +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2_grpc.py b/trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2_grpc.py new file mode 100644 index 000000000000..de3ca9f57728 --- /dev/null +++ b/trace/google/cloud/proto/devtools/cloudtrace/v1/trace_pb2_grpc.py @@ -0,0 +1,93 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + +import google.cloud.proto.devtools.cloudtrace.v1.trace_pb2 as google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2 +import google.protobuf.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_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.ListTracesRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.ListTracesResponse.FromString, + ) + self.GetTrace = channel.unary_unary( + '/google.devtools.cloudtrace.v1.TraceService/GetTrace', + request_serializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.GetTraceRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.Trace.FromString, + ) + self.PatchTraces = channel.unary_unary( + '/google.devtools.cloudtrace.v1.TraceService/PatchTraces', + request_serializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_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_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.ListTracesRequest.FromString, + response_serializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.ListTracesResponse.SerializeToString, + ), + 'GetTrace': grpc.unary_unary_rpc_method_handler( + servicer.GetTrace, + request_deserializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.GetTraceRequest.FromString, + response_serializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_dot_trace__pb2.Trace.SerializeToString, + ), + 'PatchTraces': grpc.unary_unary_rpc_method_handler( + servicer.PatchTraces, + request_deserializer=google_dot_cloud_dot_proto_dot_devtools_dot_cloudtrace_dot_v1_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,)) diff --git a/trace/google/cloud/trace.py b/trace/google/cloud/trace.py new file mode 100644 index 000000000000..d2382ffab502 --- /dev/null +++ b/trace/google/cloud/trace.py @@ -0,0 +1,24 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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.trace_v1 import enums +from google.cloud.trace_v1 import TraceServiceClient +from google.cloud.trace_v1 import types + + +__all__ = ( + 'enums', + 'TraceServiceClient', + 'types', +) diff --git a/trace/google/cloud/trace/__init__.py b/trace/google/cloud/trace/__init__.py new file mode 100644 index 000000000000..558d1302e596 --- /dev/null +++ b/trace/google/cloud/trace/__init__.py @@ -0,0 +1,18 @@ +# 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. + +from google.cloud.trace.client import Client + + +__all__ = ['Client'] diff --git a/trace/google/cloud/trace/_gax.py b/trace/google/cloud/trace/_gax.py new file mode 100644 index 000000000000..b412b54ee856 --- /dev/null +++ b/trace/google/cloud/trace/_gax.py @@ -0,0 +1,213 @@ +# 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. + +"""GAX Wrapper for interacting with the Stackdriver Trace API.""" + +from google.cloud.gapic.trace.v1 import trace_service_client +from google.cloud.proto.devtools.cloudtrace.v1 import trace_pb2 +from google.gax import CallOptions +from google.gax import INITIAL_PAGE +from google.cloud._helpers import make_secure_channel +from google.cloud._http import DEFAULT_USER_AGENT +from google.cloud.iterator import GAXIterator +from google.protobuf.json_format import MessageToDict +from google.protobuf.json_format import ParseDict + + +class _TraceAPI(object): + """Wrapper to help mapping trace-related APIs. + + See + https://cloud.google.com/trace/docs/reference/v1/rpc/google.devtools. + cloudtrace.v1 + + :type gax_api: + :class:`~google.cloud.gapic.trace.v1.trace_service_client. + TraceServiceClient` + :param gax_api: API object used to make GAX requests. + + :type client: :class:`~google.cloud.trace.client.Client` + :param client: The client that owns this API object. + """ + def __init__(self, gax_api, client): + self._gax_api = gax_api + self.client = client + + def patch_traces(self, project_id, traces, options=None): + """Sends new traces to Stackdriver Trace or updates existing traces. + + :type project_id: str + :param project_id: ID of the Cloud project where the trace data is + stored. + + :type traces: dict + :param traces: The traces to be patched in the API call. + + :type options: :class:`~google.gax.CallOptions` + :param options: (Optional) Overrides the default settings for this + call, e.g, timeout, retries etc. + """ + traces_pb = _traces_mapping_to_pb(traces) + self._gax_api.patch_traces(project_id, traces_pb, options) + + def get_trace(self, project_id, trace_id, options=None): + """Gets a single trace by its ID. + + :type project_id: str + :param project_id: ID of the Cloud project where the trace data is + stored. + + :type trace_id: str + :param trace_id: ID of the trace to return. + + :type options: :class:`~google.gax.CallOptions` + :param options: (Optional) Overrides the default settings for this + call, e.g, timeout, retries etc. + + :rtype: :dict + :returns: A Trace dict. + """ + trace_pb = self._gax_api.get_trace(project_id, trace_id, options) + 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 specified filter + conditions. + + :type project_id: str + :param project_id: ID of the Cloud project where the trace data is + stored. + + :type view: :class:`google.cloud.gapic.trace.v1.enums. + ListTracesRequest.ViewType` + :param view: (Optional) Type of data returned for traces in the list. + Default is ``MINIMAL``. + + :type page_size: int + :param 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. + + :type start_time: :class:`google.protobuf.timestamp_pb2.Timestamp` + :param start_time: (Optional) Start of the time interval (inclusive) + during which the trace data was collected from the + application. + + :type end_time: :class:`google.protobuf.timestamp_pb2.Timestamp` + :param end_time: (Optional) End of the time interval (inclusive) + during which the trace data was collected from the + application. + + :type filter_: str + :param filter_: (Optional) An optional filter for the request. + + :type order_by: str + :param order_by: (Optional) Field used to sort the returned traces. + + :type page_token: str + :param page_token: opaque marker for the next "page" of entries. If not + passed, the API will return the first page of + entries. + + :rtype: :class:`~google.cloud.iterator.Iterator` + :returns: Traces that match the specified filter conditions. + """ + if page_token is None: + page_token = INITIAL_PAGE + options = CallOptions(page_token=page_token) + page_iter = self._gax_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, + options=options) + item_to_value = _item_to_mapping + return GAXIterator(self.client, page_iter, item_to_value) + + +def _parse_trace_pb(trace_pb): + """Parse a ``Trace`` protobuf to a dictionary. + + :type trace_pb: :class:`google.cloud.proto.devtools.cloudtrace.v1. + trace_pb2.Trace` + :param trace_pb: A trace protobuf instance. + + :rtype: dict + :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 GAXIterator + + :type iterator: :class:`~google.cloud.iterator.Iterator` + :param iterator: The iterator that is currently in use. + + :type trace_pb: :class:`google.cloud.proto.devtools.cloudtrace.v1. + trace_pb2.Trace` + :param trace_pb: A trace protobuf instance. + """ + mapping = _parse_trace_pb(trace_pb) + return mapping + + +def make_gax_trace_api(client): + """Create an instance of the GAX Trace API. + + :type client: :class:`~google.cloud.trace.client.Client` + :param client: The client that holds configuration details. + + :rtype: :class:`~google.cloud.trace._gax._TraceAPI` + :returns: A Trace API instance with the proper configurations. + """ + channel = make_secure_channel( + client._credentials, + DEFAULT_USER_AGENT, + trace_service_client.TraceServiceClient.SERVICE_ADDRESS) + generated = trace_service_client.TraceServiceClient( + channel=channel, + lib_name='gccl') + return _TraceAPI(generated, client) + + +def _traces_mapping_to_pb(traces_mapping): + """Convert a trace dict to protobuf. + + :type traces_mapping: dict + :param traces_mapping: A trace mapping. + + :rtype: class:`google.cloud.proto.devtools.cloudtrace.v1.trace_pb2.Traces` + :returns: The converted protobuf type traces. + """ + traces_pb = trace_pb2.Traces() + ParseDict(traces_mapping, traces_pb) + return traces_pb diff --git a/trace/google/cloud/trace/client.py b/trace/google/cloud/trace/client.py new file mode 100644 index 000000000000..d2104924a2bf --- /dev/null +++ b/trace/google/cloud/trace/client.py @@ -0,0 +1,167 @@ +# 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. + +"""Client for interacting with the Stackdriver Trace API.""" + +from google.cloud.trace._gax import make_gax_trace_api +from google.cloud.client import ClientWithProject +from google.cloud._helpers import _datetime_to_pb_timestamp + + +class Client(ClientWithProject): + """Client to bundle configuration needed for API requests. + + :type project: str + :param project: The project which the client acts on behalf of. + If not passed, falls back to the default inferred from + the environment. + + :type credentials: :class:`~google.auth.credentials.Credentials` + :param credentials: (Optional) The OAuth2 Credentials to use for this + client. If not passed, falls back to the default + inferred from the environment. + """ + _trace_api = None + + def __init__(self, project=None, credentials=None): + super(Client, self).__init__( + project=project, credentials=credentials) + + @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 + """ + self._trace_api = make_gax_trace_api(self) + return self._trace_api + + def patch_traces(self, traces, project_id=None, options=None): + """Sends new traces to Stackdriver Trace or updates existing traces. + + :type traces: dict + :param traces: The traces to be patched in the API call. + + :type project_id: str + :param project_id: (Optional) ID of the Cloud project where the trace + data is stored. + + :type options: :class:`~google.gax.CallOptions` + :param options: (Optional) Overrides the default settings for this + call, e.g, timeout, retries etc. + """ + if project_id is None: + project_id = self.project + + self.trace_api.patch_traces( + project_id=project_id, + traces=traces, + options=options) + + def get_trace(self, trace_id, project_id=None, options=None): + """Gets a single trace by its ID. + + :type project_id: str + :param project_id: ID of the Cloud project where the trace data is + stored. + + :type trace_id: str + :param trace_id: ID of the trace to return. + + :type options: :class:`~google.gax.CallOptions` + :param options: (Optional) Overrides the default settings for this + call, e.g, timeout, retries etc. + + :rtype: dict + :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, + options=options) + + 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. + + :type project_id: str + :param project_id: (Optional) ID of the Cloud project where the trace + data is stored. + + :type view: :class:`google.cloud.gapic.trace.v1.enums. + ListTracesRequest.ViewType` + :param view: (Optional) Type of data returned for traces in the list. + Default is ``MINIMAL``. + + :type page_size: int + :param 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. + + :type start_time: :class:`~datetime.datetime` + :param start_time: (Optional) Start of the time interval (inclusive) + during which the trace data was collected from the + application. + + :type end_time: :class:`~datetime.datetime` + :param end_time: (Optional) End of the time interval (inclusive) during + which the trace data was collected from the + application. + + :type filter_: str + :param filter_: (Optional) An optional filter for the request. + + :type order_by: str + :param order_by: (Optional) Field used to sort the returned traces. + + :type page_token: str + :param page_token: opaque marker for the next "page" of entries. If not + passed, the API will return the first page of + entries. + + :rtype: :class:`~google.cloud.iterator.Iterator` + :returns: 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/trace/google/cloud/trace_v1/__init__.py b/trace/google/cloud/trace_v1/__init__.py new file mode 100644 index 000000000000..8d4fa6bd3c39 --- /dev/null +++ b/trace/google/cloud/trace_v1/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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.gapic.trace.v1.trace_service_client import TraceServiceClient +from google.cloud.gapic.trace.v1 import enums + +from google.cloud.trace_v1 import types + + +__all__ = ( + 'enums', + 'TraceServiceClient', + 'types', +) diff --git a/trace/google/cloud/trace_v1/types.py b/trace/google/cloud/trace_v1/types.py new file mode 100644 index 000000000000..ed6d5b585829 --- /dev/null +++ b/trace/google/cloud/trace_v1/types.py @@ -0,0 +1,28 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 absolute_import +import sys + +from google.cloud.proto.devtools.cloudtrace.v1 import trace_pb2 +from google.gax.utils.messages import get_messages + + +names = [] +for name, message in get_messages(trace_pb2).items(): + setattr(sys.modules[__name__], name, message) + names.append(name) + + +__all__ = tuple(sorted(names)) diff --git a/trace/nox.py b/trace/nox.py new file mode 100644 index 000000000000..08c69cb85df5 --- /dev/null +++ b/trace/nox.py @@ -0,0 +1,79 @@ +# Copyright 2016 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. + +from __future__ import absolute_import + +import nox + + +LOCAL_DEPS = ('../core/',) + + +@nox.session +@nox.parametrize('python_version', ['2.7', '3.4', '3.5', '3.6']) +def unit_tests(session, python_version): + """Run the unit test suite.""" + + # Run unit tests against all supported versions of Python. + session.interpreter = 'python{}'.format(python_version) + + # Install all test dependencies, then install this package in-place. + session.install('mock', 'pytest', 'pytest-cov', *LOCAL_DEPS) + session.install('-e', '.') + + # Run py.test against the unit tests. + session.run( + 'py.test', + '--quiet', + '--cov=google.cloud.trace', + '--cov-append', + '--cov-config=.coveragerc', + '--cov-report=', + '--cov-fail-under=97', + 'tests/', + *session.posargs + ) + + +@nox.session +def lint(session): + """Run flake8. + Returns a failure if flake8 finds linting errors or sufficiently + serious code quality issues. + """ + session.interpreter = 'python3.6' + session.install('flake8', *LOCAL_DEPS) + session.install('.') + session.run('flake8', 'google/cloud/trace') + + +@nox.session +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.interpreter = 'python3.6' + session.install('docutils', 'pygments') + session.run( + 'python', 'setup.py', 'check', '--restructuredtext', '--strict') + + +@nox.session +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.interpreter = 'python3.6' + session.install('coverage', 'pytest-cov') + session.run('coverage', 'report', '--show-missing', '--fail-under=100') + session.run('coverage', 'erase') diff --git a/trace/setup.py b/trace/setup.py new file mode 100644 index 000000000000..aeeae31756e4 --- /dev/null +++ b/trace/setup.py @@ -0,0 +1,44 @@ +"""A setup module for the GAPIC Stackdriver Trace API library. + +See: +https://packaging.python.org/en/latest/distributing.html +https://github.com/pypa/sampleproject +""" + +from setuptools import setup, find_packages + +install_requires = [ + 'google-gax>=0.15.7, <0.16dev', + 'googleapis-common-protos[grpc]>=1.5.2, <2.0dev', + 'google-cloud-core >= 0.24.0, < 0.25dev', +] + +setup( + name='google-cloud-trace', + version='0.15.4', + author='Google Inc', + author_email='googleapis-packages@google.com', + classifiers=[ + 'Intended Audience :: Developers', + 'Development Status :: 3 - Alpha', + '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.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: Implementation :: CPython', + ], + description='GAPIC library for the Stackdriver Trace API', + include_package_data=True, + long_description=open('README.rst').read(), + install_requires=install_requires, + license='Apache-2.0', + packages=find_packages(), + namespace_packages=[ + 'google', 'google.cloud', 'google.cloud.gapic', + 'google.cloud.gapic.trace' + ], + url='https://github.com/googleapis/googleapis') diff --git a/trace/tests/__init__.py b/trace/tests/__init__.py new file mode 100644 index 000000000000..7c07b241f066 --- /dev/null +++ b/trace/tests/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/trace/tests/gapic/v1/test_trace_service_client_v1.py b/trace/tests/gapic/v1/test_trace_service_client_v1.py new file mode 100644 index 000000000000..c9ca3b6d1629 --- /dev/null +++ b/trace/tests/gapic/v1/test_trace_service_client_v1.py @@ -0,0 +1,177 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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. +"""Unit tests.""" + +import mock +import unittest + +from google.gax import errors + +from google.cloud.gapic.trace.v1 import trace_service_client +from google.cloud.proto.devtools.cloudtrace.v1 import trace_pb2 +from google.protobuf import empty_pb2 + + +class CustomException(Exception): + pass + + +class TestTraceServiceClient(unittest.TestCase): + @mock.patch('google.gax.config.create_stub', spec=True) + def test_patch_traces(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = trace_service_client.TraceServiceClient() + + # Mock request + project_id = 'projectId-1969970175' + traces = trace_pb2.Traces() + + client.patch_traces(project_id, traces) + + grpc_stub.PatchTraces.assert_called_once() + args, kwargs = grpc_stub.PatchTraces.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = trace_pb2.PatchTracesRequest( + project_id=project_id, traces=traces) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_patch_traces_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = trace_service_client.TraceServiceClient() + + # Mock request + project_id = 'projectId-1969970175' + traces = trace_pb2.Traces() + + # Mock exception response + grpc_stub.PatchTraces.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.patch_traces, project_id, + traces) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_trace(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = trace_service_client.TraceServiceClient() + + # Mock request + project_id = 'projectId-1969970175' + trace_id = 'traceId1270300245' + + # Mock response + project_id_2 = 'projectId2939242356' + trace_id_2 = 'traceId2987826376' + expected_response = trace_pb2.Trace( + project_id=project_id_2, trace_id=trace_id_2) + grpc_stub.GetTrace.return_value = expected_response + + response = client.get_trace(project_id, trace_id) + self.assertEqual(expected_response, response) + + grpc_stub.GetTrace.assert_called_once() + args, kwargs = grpc_stub.GetTrace.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = trace_pb2.GetTraceRequest( + project_id=project_id, trace_id=trace_id) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_trace_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = trace_service_client.TraceServiceClient() + + # Mock request + project_id = 'projectId-1969970175' + trace_id = 'traceId1270300245' + + # Mock exception response + grpc_stub.GetTrace.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_trace, project_id, + trace_id) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_traces(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = trace_service_client.TraceServiceClient() + + # Mock request + project_id = 'projectId-1969970175' + + # Mock response + next_page_token = '' + traces_element = trace_pb2.Trace() + traces = [traces_element] + expected_response = trace_pb2.ListTracesResponse( + next_page_token=next_page_token, traces=traces) + grpc_stub.ListTraces.return_value = expected_response + + paged_list_response = client.list_traces(project_id) + resources = list(paged_list_response) + self.assertEqual(1, len(resources)) + self.assertEqual(expected_response.traces[0], resources[0]) + + grpc_stub.ListTraces.assert_called_once() + args, kwargs = grpc_stub.ListTraces.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = trace_pb2.ListTracesRequest(project_id=project_id) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_traces_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = trace_service_client.TraceServiceClient() + + # Mock request + project_id = 'projectId-1969970175' + + # Mock exception response + grpc_stub.ListTraces.side_effect = CustomException() + + paged_list_response = client.list_traces(project_id) + self.assertRaises(errors.GaxError, list, paged_list_response) diff --git a/trace/tests/unit/test__gax.py b/trace/tests/unit/test__gax.py new file mode 100644 index 000000000000..3f950021b85e --- /dev/null +++ b/trace/tests/unit/test__gax.py @@ -0,0 +1,429 @@ +# 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. + +import unittest + +import mock + +from google.cloud._testing import _GAXBaseAPI + + +class _Base(object): + project = 'PROJECT' + + 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._gax import _TraceAPI + + return _TraceAPI + + def test_constructor(self): + gax_api = object() + client = object() + api = self._make_one(gax_api, client) + self.assertIs(api._gax_api, gax_api) + self.assertIs(api.client, client) + + def test_patch_traces(self): + from google.cloud.gapic.trace.v1 import trace_service_client + from google.cloud.proto.devtools.cloudtrace.v1.trace_pb2 import ( + TraceSpan, Trace, Traces) + from google.cloud.trace._gax import _traces_mapping_to_pb + from google.cloud._helpers import _datetime_to_pb_timestamp + + from datetime import datetime + + trace_id = 'test_trace_id' + span_id = 1234 + span_name = 'test_span_name' + start_time = datetime.utcnow() + end_time = 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) + + gax_api = mock.Mock(spec=trace_service_client.TraceServiceClient) + api = self._make_one(gax_api, None) + api.patch_traces(project_id=self.project, traces=traces) + + gax_api.patch_traces.assert_called_with(self.project, traces_pb, None) + + call_args = gax_api.patch_traces.call_args[0] + self.assertEqual(len(call_args), 3) + traces_called = call_args[1] + self.assertEqual(len(traces_called.traces), 1) + trace = traces_called.traces[0] + + self.assertEqual(len(trace.spans), 1) + span = trace.spans[0] + + self.assertIsInstance(traces_called, Traces) + self.assertEqual(trace.project_id, self.project) + self.assertEqual(trace.trace_id, trace_id) + self.assertIsInstance(trace, Trace) + + self.assertEqual(span.span_id, span_id) + self.assertEqual(span.name, span_name) + self.assertEqual( + span.start_time, + _datetime_to_pb_timestamp(start_time)) + self.assertEqual( + span.end_time, + _datetime_to_pb_timestamp(end_time)) + self.assertIsInstance(span, TraceSpan) + + def test_get_trace(self): + from google.cloud.gapic.trace.v1 import trace_service_client + + trace_id = 'test_trace_id' + + gax_api = mock.Mock(spec=trace_service_client.TraceServiceClient) + api = self._make_one(gax_api, None) + patch = mock.patch('google.cloud.trace._gax._parse_trace_pb', + return_value='fake_pb_result') + + with patch: + api.get_trace(project_id=self.project, trace_id=trace_id) + + gax_api.get_trace.assert_called_with(self.project, trace_id, None) + + def _make_trace_pb( + self, + project, + trace_id, + span_id, + span_name, + start_time, + end_time, + parent_span_id, + labels): + from google.cloud.trace._gax import _traces_mapping_to_pb + + span_kind = 2 + + traces = { + 'traces': [ + { + 'projectId': project, + 'traceId': trace_id, + 'spans': [ + { + 'spanId': span_id, + 'name': span_name, + 'startTime': start_time, + 'endTime': end_time, + 'kind': span_kind, + 'parentSpanId': parent_span_id, + 'labels': labels, + }, + ], + }, + ], + } + + traces_pb = _traces_mapping_to_pb(traces) + trace_pb = traces_pb.traces + return trace_pb + + def test_list_traces_no_paging(self): + from google.cloud._testing import _GAXPageIterator + from google.cloud.gapic.trace.v1 import trace_service_client + from google.cloud.gapic.trace.v1.enums import ListTracesRequest as Enum + from google.gax import INITIAL_PAGE + + from datetime import datetime + + trace_id = 'test_trace_id' + span_id = 1234 + span_name = 'test_span_name' + span_kind = 'RPC_CLIENT' + parent_span_id = 123 + start_time = datetime.utcnow().isoformat() + 'Z' + end_time = datetime.utcnow().isoformat() + 'Z' + labels = { + '/http/status_code': '200', + '/component': 'HTTP load balancer', + } + size = 10 + view_type = Enum.ViewType.COMPLETE + + trace_pb = self._make_trace_pb( + self.project, + trace_id, + span_id, + span_name, + start_time, + end_time, + parent_span_id, + labels) + + response = _GAXPageIterator(trace_pb) + gax_api = mock.Mock(spec=trace_service_client.TraceServiceClient) + gax_api.list_traces.return_value = response + api = self._make_one(gax_api, None) + + iterator = api.list_traces( + project_id=self.project, + view=view_type, + page_size=size) + + traces = list(iterator) + + self.assertEqual(len(traces), 1) + trace = traces[0] + + self.assertEqual(len(trace['spans']), 1) + span = trace['spans'][0] + + self.assertEqual(trace['projectId'], self.project) + self.assertEqual(trace['traceId'], trace_id) + + self.assertEqual(span['spanId'], str(span_id)) + self.assertEqual(span['name'], span_name) + + self.assertEqual( + span['startTime'], start_time) + self.assertEqual( + span['endTime'], end_time) + self.assertEqual(span['kind'], span_kind) + self.assertEqual(span['parentSpanId'], str(parent_span_id)) + self.assertEqual(span['labels'], labels) + + call_args = gax_api.list_traces.call_args[1] + + self.assertEqual(call_args['project_id'], self.project) + self.assertEqual(call_args['view'], view_type) + self.assertEqual(call_args['page_size'], size) + self.assertIsNone(call_args['start_time']) + self.assertIsNone(call_args['end_time']) + self.assertIsNone(call_args['filter_']) + self.assertIsNone(call_args['order_by']) + self.assertEqual(call_args['options'].page_token, INITIAL_PAGE) + + def test_list_traces_with_paging(self): + from google.cloud._testing import _GAXPageIterator + from google.cloud.gapic.trace.v1 import trace_service_client + from google.cloud.gapic.trace.v1.enums import ListTracesRequest as Enum + + from datetime import datetime + + trace_id = 'test_trace_id' + span_id = 1234 + span_name = 'test_span_name' + span_kind = 'RPC_CLIENT' + parent_span_id = 123 + start_time = datetime.utcnow().isoformat() + 'Z' + end_time = datetime.utcnow().isoformat() + 'Z' + labels = { + '/http/status_code': '200', + '/component': 'HTTP load balancer', + } + size = 10 + view_type = Enum.ViewType.COMPLETE + token = 'TOKEN' + + trace_pb = self._make_trace_pb( + self.project, + trace_id, + span_id, + span_name, + start_time, + end_time, + parent_span_id, + labels) + + response = _GAXPageIterator(trace_pb) + gax_api = mock.Mock(spec=trace_service_client.TraceServiceClient) + gax_api.list_traces.return_value = response + api = self._make_one(gax_api, None) + + iterator = api.list_traces( + project_id=self.project, + view=view_type, + page_size=size, + page_token=token) + + traces = list(iterator) + + self.assertEqual(len(traces), 1) + trace = traces[0] + + self.assertEqual(len(trace['spans']), 1) + span = trace['spans'][0] + + self.assertEqual(trace['projectId'], self.project) + self.assertEqual(trace['traceId'], trace_id) + + self.assertEqual(span['spanId'], str(span_id)) + self.assertEqual(span['name'], span_name) + + self.assertEqual( + span['startTime'], start_time) + self.assertEqual( + span['endTime'], end_time) + self.assertEqual(span['kind'], span_kind) + self.assertEqual(span['parentSpanId'], str(parent_span_id)) + self.assertEqual(span['labels'], labels) + + call_args = gax_api.list_traces.call_args[1] + + self.assertEqual(call_args['project_id'], self.project) + self.assertEqual(call_args['view'], view_type) + self.assertEqual(call_args['page_size'], size) + self.assertIsNone(call_args['start_time']) + self.assertIsNone(call_args['end_time']) + self.assertIsNone(call_args['filter_']) + self.assertIsNone(call_args['order_by']) + self.assertEqual(call_args['options'].page_token, token) + + +class Test__parse_trace_pb(unittest.TestCase): + + @staticmethod + def _call_fut(*args, **kwargs): + from google.cloud.trace._gax import _parse_trace_pb + + return _parse_trace_pb(*args, **kwargs) + + def test_registered_type(self): + from google.cloud.proto.devtools.cloudtrace.v1.trace_pb2 import ( + TraceSpan, Trace) + from google.protobuf.timestamp_pb2 import Timestamp + + 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 + + start_time_pb = Timestamp(seconds=start_seconds, nanos=start_nanos) + end_time_pb = Timestamp(seconds=end_seconds, nanos=end_nanos) + + span_pb = TraceSpan( + span_id=span_id, + name=span_name, + start_time=start_time_pb, + end_time=end_time_pb) + + trace_pb = Trace( + project_id=project, + trace_id=trace_id, + spans=[span_pb]) + + parse_result = self._call_fut(trace_pb) + + expected_result = { + 'projectId': project, + 'traceId': trace_id, + 'spans': [ + { + 'spanId': str(span_id), + 'name': span_name, + 'startTime': start_time, + 'endTime': end_time, + }, + ], + } + + self.assertEqual(parse_result, expected_result) + + @mock.patch('google.cloud.trace._gax.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_gax_trace_api(unittest.TestCase): + + def _call_fut(self, client): + from google.cloud.trace._gax import make_gax_trace_api + + return make_gax_trace_api(client) + + def test_it(self): + from google.cloud.trace._gax import _TraceAPI + from google.cloud._http import DEFAULT_USER_AGENT + + credentials = object() + client = mock.Mock(_credentials=credentials, spec=['_credentials']) + channels = [] + channel_args = [] + generated_api_kwargs = [] + channel_obj = object() + generated = object() + + def make_channel(*args): + channel_args.append(args) + return channel_obj + + def generated_api(channel=None, **kwargs): + channels.append(channel) + generated_api_kwargs.append(kwargs) + return generated + + host = 'foo.apis.invalid' + generated_api.SERVICE_ADDRESS = host + + patch_channel = mock.patch( + 'google.cloud.trace._gax.make_secure_channel', + new=make_channel) + + patch_api = mock.patch( + 'google.cloud.trace._gax.trace_service_client.TraceServiceClient', + new=generated_api) + + with patch_api: + with patch_channel: + trace_api = self._call_fut(client) + + self.assertEqual(channels, [channel_obj]) + self.assertEqual(channel_args, + [(credentials, DEFAULT_USER_AGENT, host)]) + + self.assertEqual(len(generated_api_kwargs), 1) + self.assertEqual(generated_api_kwargs[0]['lib_name'], 'gccl') + + self.assertIsInstance(trace_api, _TraceAPI) + self.assertIs(trace_api._gax_api, generated) + self.assertIs(trace_api.client, client) diff --git a/trace/tests/unit/test_client.py b/trace/tests/unit/test_client.py new file mode 100644 index 000000000000..62cc8ad8e9f2 --- /dev/null +++ b/trace/tests/unit/test_client.py @@ -0,0 +1,252 @@ +# 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. + +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(self): + credentials = _make_credentials() + client = self._make_one(project=self.project, credentials=credentials) + self.assertEqual(client.project, self.project) + + 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_gax_trace_api', + new=make_api) + + with patch: + api = client.trace_api + + self.assertIs(api, api_obj) + self.assertEqual(clients, [client]) + + def test_patch_traces_default(self): + from google.cloud.trace._gax 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.client.make_gax_trace_api', return_value=mock_trace_api) + + with patch: + client.patch_traces(traces=traces) + + mock_trace_api.patch_traces.assert_called_with( + options=None, + project_id='PROJECT', + traces='fake_traces_for_test') + + def test_patch_traces_explicit(self): + from google.cloud.trace._gax 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.client.make_gax_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( + options=None, + project_id='PROJECT', + traces='fake_traces_for_test') + + def test_get_trace_default(self): + from google.cloud.trace._gax 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.client.make_gax_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._gax 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.client.make_gax_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._gax 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.client.make_gax_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.gapic.trace.v1.enums import ListTracesRequest as Enum + from google.cloud.trace._gax 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.client.make_gax_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))