From 6d6dc42337e84930022f8e0441f3beaf28bf512e Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 22 Jun 2021 00:09:50 +0000 Subject: [PATCH 1/4] chore: remove all monolith Bazel deps chore: release gapic-generator-csharp v1.3.7 chore: release gapic-generator-go 0.20.5 chore: release gapic-generator-java 1.0.14 chore: release gapic-generator-php 1.0.1 chore: release gapic-generator-python 0.50.0 chore: update gapic-generator-ruby to the latest commit chore: release gapic-generator-typescript 1.5.0 Committer: @miraleung PiperOrigin-RevId: 380641501 Source-Link: https://github.com/googleapis/googleapis/commit/076f7e9f0b258bdb54338895d7251b202e8f0de3 Source-Link: https://github.com/googleapis/googleapis-gen/commit/27e4c88b4048e5f56508d4e1aa417d60a3380892 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++++ .../docs/dashboard_v1/dashboards_service.rst | 10 + .../v1/docs/dashboard_v1/services.rst | 6 + .../v1/docs/dashboard_v1/types.rst | 7 + owl-bot-staging/v1/docs/index.rst | 7 + .../google/monitoring/dashboard/__init__.py | 71 + .../v1/google/monitoring/dashboard/py.typed | 2 + .../monitoring/dashboard_v1/__init__.py | 72 + .../dashboard_v1/gapic_metadata.json | 73 + .../google/monitoring/dashboard_v1/py.typed | 2 + .../dashboard_v1/services/__init__.py | 15 + .../services/dashboards_service/__init__.py | 22 + .../dashboards_service/async_client.py | 471 ++++ .../services/dashboards_service/client.py | 663 ++++++ .../services/dashboards_service/pagers.py | 141 ++ .../dashboards_service/transports/__init__.py | 33 + .../dashboards_service/transports/base.py | 229 ++ .../dashboards_service/transports/grpc.py | 382 ++++ .../transports/grpc_asyncio.py | 386 ++++ .../monitoring/dashboard_v1/types/__init__.py | 84 + .../monitoring/dashboard_v1/types/common.py | 298 +++ .../dashboard_v1/types/dashboard.py | 102 + .../dashboard_v1/types/dashboards_service.py | 175 ++ .../dashboard_v1/types/drilldowns.py | 25 + .../monitoring/dashboard_v1/types/layouts.py | 214 ++ .../monitoring/dashboard_v1/types/metrics.py | 269 +++ .../dashboard_v1/types/scorecard.py | 167 ++ .../monitoring/dashboard_v1/types/service.py | 25 + .../monitoring/dashboard_v1/types/text.py | 52 + .../monitoring/dashboard_v1/types/widget.py | 80 + .../monitoring/dashboard_v1/types/xychart.py | 182 ++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 ++ .../v1/scripts/fixup_dashboard_v1_keywords.py | 180 ++ owl-bot-staging/v1/setup.py | 53 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/dashboard_v1/__init__.py | 16 + .../dashboard_v1/test_dashboards_service.py | 1924 +++++++++++++++++ 43 files changed, 7065 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst create mode 100644 owl-bot-staging/v1/docs/dashboard_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/dashboard_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard/__init__.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard/py.typed create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py create mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..587e3dd --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/monitoring/dashboard/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..2da1894 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/monitoring/dashboard *.py +recursive-include google/monitoring/dashboard_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..12344c5 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Monitoring Dashboard API +================================================= + +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 billing for your project.`_ +3. Enable the Google Monitoring Dashboard API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +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 + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..c2a0bf9 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-monitoring-dashboard 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.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# 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.todo", + "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"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# 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-monitoring-dashboard" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = "alabaster" + +# 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 = { + "description": "Google Monitoring Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# 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 = ["_static"] + +# 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-monitoring-dashboard-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- 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-monitoring-dashboard.tex", + u"google-monitoring-dashboard 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-monitoring-dashboard", + u"Google Monitoring Dashboard 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-monitoring-dashboard", + u"google-monitoring-dashboard Documentation", + author, + "google-monitoring-dashboard", + "GAPIC library for Google Monitoring Dashboard API", + "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), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/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/owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst b/owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst new file mode 100644 index 0000000..91f68ce --- /dev/null +++ b/owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst @@ -0,0 +1,10 @@ +DashboardsService +----------------------------------- + +.. automodule:: google.monitoring.dashboard_v1.services.dashboards_service + :members: + :inherited-members: + +.. automodule:: google.monitoring.dashboard_v1.services.dashboards_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/dashboard_v1/services.rst b/owl-bot-staging/v1/docs/dashboard_v1/services.rst new file mode 100644 index 0000000..bfcc085 --- /dev/null +++ b/owl-bot-staging/v1/docs/dashboard_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Monitoring Dashboard v1 API +=============================================== +.. toctree:: + :maxdepth: 2 + + dashboards_service diff --git a/owl-bot-staging/v1/docs/dashboard_v1/types.rst b/owl-bot-staging/v1/docs/dashboard_v1/types.rst new file mode 100644 index 0000000..56014d5 --- /dev/null +++ b/owl-bot-staging/v1/docs/dashboard_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Monitoring Dashboard v1 API +============================================ + +.. automodule:: google.monitoring.dashboard_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..41b71cf --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + dashboard_v1/services + dashboard_v1/types diff --git a/owl-bot-staging/v1/google/monitoring/dashboard/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard/__init__.py new file mode 100644 index 0000000..dd8fd5a --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard/__init__.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.monitoring.dashboard_v1.services.dashboards_service.client import DashboardsServiceClient +from google.monitoring.dashboard_v1.services.dashboards_service.async_client import DashboardsServiceAsyncClient + +from google.monitoring.dashboard_v1.types.common import Aggregation +from google.monitoring.dashboard_v1.types.common import PickTimeSeriesFilter +from google.monitoring.dashboard_v1.types.common import StatisticalTimeSeriesFilter +from google.monitoring.dashboard_v1.types.dashboard import Dashboard +from google.monitoring.dashboard_v1.types.dashboards_service import CreateDashboardRequest +from google.monitoring.dashboard_v1.types.dashboards_service import DeleteDashboardRequest +from google.monitoring.dashboard_v1.types.dashboards_service import GetDashboardRequest +from google.monitoring.dashboard_v1.types.dashboards_service import ListDashboardsRequest +from google.monitoring.dashboard_v1.types.dashboards_service import ListDashboardsResponse +from google.monitoring.dashboard_v1.types.dashboards_service import UpdateDashboardRequest +from google.monitoring.dashboard_v1.types.layouts import ColumnLayout +from google.monitoring.dashboard_v1.types.layouts import GridLayout +from google.monitoring.dashboard_v1.types.layouts import MosaicLayout +from google.monitoring.dashboard_v1.types.layouts import RowLayout +from google.monitoring.dashboard_v1.types.metrics import Threshold +from google.monitoring.dashboard_v1.types.metrics import TimeSeriesFilter +from google.monitoring.dashboard_v1.types.metrics import TimeSeriesFilterRatio +from google.monitoring.dashboard_v1.types.metrics import TimeSeriesQuery +from google.monitoring.dashboard_v1.types.metrics import SparkChartType +from google.monitoring.dashboard_v1.types.scorecard import Scorecard +from google.monitoring.dashboard_v1.types.text import Text +from google.monitoring.dashboard_v1.types.widget import Widget +from google.monitoring.dashboard_v1.types.xychart import ChartOptions +from google.monitoring.dashboard_v1.types.xychart import XyChart + +__all__ = ('DashboardsServiceClient', + 'DashboardsServiceAsyncClient', + 'Aggregation', + 'PickTimeSeriesFilter', + 'StatisticalTimeSeriesFilter', + 'Dashboard', + 'CreateDashboardRequest', + 'DeleteDashboardRequest', + 'GetDashboardRequest', + 'ListDashboardsRequest', + 'ListDashboardsResponse', + 'UpdateDashboardRequest', + 'ColumnLayout', + 'GridLayout', + 'MosaicLayout', + 'RowLayout', + 'Threshold', + 'TimeSeriesFilter', + 'TimeSeriesFilterRatio', + 'TimeSeriesQuery', + 'SparkChartType', + 'Scorecard', + 'Text', + 'Widget', + 'ChartOptions', + 'XyChart', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard/py.typed b/owl-bot-staging/v1/google/monitoring/dashboard/py.typed new file mode 100644 index 0000000..a52708e --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-monitoring-dashboard package uses inline types. diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py new file mode 100644 index 0000000..d297765 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.dashboards_service import DashboardsServiceClient +from .services.dashboards_service import DashboardsServiceAsyncClient + +from .types.common import Aggregation +from .types.common import PickTimeSeriesFilter +from .types.common import StatisticalTimeSeriesFilter +from .types.dashboard import Dashboard +from .types.dashboards_service import CreateDashboardRequest +from .types.dashboards_service import DeleteDashboardRequest +from .types.dashboards_service import GetDashboardRequest +from .types.dashboards_service import ListDashboardsRequest +from .types.dashboards_service import ListDashboardsResponse +from .types.dashboards_service import UpdateDashboardRequest +from .types.layouts import ColumnLayout +from .types.layouts import GridLayout +from .types.layouts import MosaicLayout +from .types.layouts import RowLayout +from .types.metrics import Threshold +from .types.metrics import TimeSeriesFilter +from .types.metrics import TimeSeriesFilterRatio +from .types.metrics import TimeSeriesQuery +from .types.metrics import SparkChartType +from .types.scorecard import Scorecard +from .types.text import Text +from .types.widget import Widget +from .types.xychart import ChartOptions +from .types.xychart import XyChart + +__all__ = ( + 'DashboardsServiceAsyncClient', +'Aggregation', +'ChartOptions', +'ColumnLayout', +'CreateDashboardRequest', +'Dashboard', +'DashboardsServiceClient', +'DeleteDashboardRequest', +'GetDashboardRequest', +'GridLayout', +'ListDashboardsRequest', +'ListDashboardsResponse', +'MosaicLayout', +'PickTimeSeriesFilter', +'RowLayout', +'Scorecard', +'SparkChartType', +'StatisticalTimeSeriesFilter', +'Text', +'Threshold', +'TimeSeriesFilter', +'TimeSeriesFilterRatio', +'TimeSeriesQuery', +'UpdateDashboardRequest', +'Widget', +'XyChart', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json b/owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json new file mode 100644 index 0000000..94b72f3 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json @@ -0,0 +1,73 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.monitoring.dashboard_v1", + "protoPackage": "google.monitoring.dashboard.v1", + "schema": "1.0", + "services": { + "DashboardsService": { + "clients": { + "grpc": { + "libraryClient": "DashboardsServiceClient", + "rpcs": { + "CreateDashboard": { + "methods": [ + "create_dashboard" + ] + }, + "DeleteDashboard": { + "methods": [ + "delete_dashboard" + ] + }, + "GetDashboard": { + "methods": [ + "get_dashboard" + ] + }, + "ListDashboards": { + "methods": [ + "list_dashboards" + ] + }, + "UpdateDashboard": { + "methods": [ + "update_dashboard" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DashboardsServiceAsyncClient", + "rpcs": { + "CreateDashboard": { + "methods": [ + "create_dashboard" + ] + }, + "DeleteDashboard": { + "methods": [ + "delete_dashboard" + ] + }, + "GetDashboard": { + "methods": [ + "get_dashboard" + ] + }, + "ListDashboards": { + "methods": [ + "list_dashboards" + ] + }, + "UpdateDashboard": { + "methods": [ + "update_dashboard" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed b/owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed new file mode 100644 index 0000000..a52708e --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-monitoring-dashboard package uses inline types. diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py new file mode 100644 index 0000000..879347b --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DashboardsServiceClient +from .async_client import DashboardsServiceAsyncClient + +__all__ = ( + 'DashboardsServiceClient', + 'DashboardsServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py new file mode 100644 index 0000000..e1a5eca --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py @@ -0,0 +1,471 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.monitoring.dashboard_v1.services.dashboards_service import pagers +from google.monitoring.dashboard_v1.types import dashboard +from google.monitoring.dashboard_v1.types import dashboards_service +from google.monitoring.dashboard_v1.types import layouts +from .transports.base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport +from .client import DashboardsServiceClient + + +class DashboardsServiceAsyncClient: + """Manages Stackdriver dashboards. A dashboard is an arrangement + of data display widgets in a specific layout. + """ + + _client: DashboardsServiceClient + + DEFAULT_ENDPOINT = DashboardsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DashboardsServiceClient.DEFAULT_MTLS_ENDPOINT + + dashboard_path = staticmethod(DashboardsServiceClient.dashboard_path) + parse_dashboard_path = staticmethod(DashboardsServiceClient.parse_dashboard_path) + common_billing_account_path = staticmethod(DashboardsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DashboardsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DashboardsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DashboardsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DashboardsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DashboardsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DashboardsServiceClient.common_project_path) + parse_common_project_path = staticmethod(DashboardsServiceClient.parse_common_project_path) + common_location_path = staticmethod(DashboardsServiceClient.common_location_path) + parse_common_location_path = staticmethod(DashboardsServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DashboardsServiceAsyncClient: The constructed client. + """ + return DashboardsServiceClient.from_service_account_info.__func__(DashboardsServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DashboardsServiceAsyncClient: The constructed client. + """ + return DashboardsServiceClient.from_service_account_file.__func__(DashboardsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DashboardsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DashboardsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DashboardsServiceClient).get_transport_class, type(DashboardsServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DashboardsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dashboards service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DashboardsServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DashboardsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_dashboard(self, + request: dashboards_service.CreateDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Creates a new custom dashboard. For examples on how you can use + this API to create dashboards, see `Managing dashboards by + API `__. + This method requires the ``monitoring.dashboards.create`` + permission on the specified project. For more information about + permissions, see `Cloud Identity and Access + Management `__. + + Args: + request (:class:`google.monitoring.dashboard_v1.types.CreateDashboardRequest`): + The request object. The `CreateDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.types.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + # Create or coerce a protobuf request object. + request = dashboards_service.CreateDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_dashboard, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_dashboards(self, + request: dashboards_service.ListDashboardsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDashboardsAsyncPager: + r"""Lists the existing dashboards. + + This method requires the ``monitoring.dashboards.list`` + permission on the specified project. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (:class:`google.monitoring.dashboard_v1.types.ListDashboardsRequest`): + The request object. The `ListDashboards` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.services.dashboards_service.pagers.ListDashboardsAsyncPager: + The ListDashboards request. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = dashboards_service.ListDashboardsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_dashboards, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDashboardsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_dashboard(self, + request: dashboards_service.GetDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Fetches a specific dashboard. + + This method requires the ``monitoring.dashboards.get`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (:class:`google.monitoring.dashboard_v1.types.GetDashboardRequest`): + The request object. The `GetDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.types.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + # Create or coerce a protobuf request object. + request = dashboards_service.GetDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_dashboard, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_dashboard(self, + request: dashboards_service.DeleteDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing custom dashboard. + + This method requires the ``monitoring.dashboards.delete`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (:class:`google.monitoring.dashboard_v1.types.DeleteDashboardRequest`): + The request object. The `DeleteDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = dashboards_service.DeleteDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_dashboard, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_dashboard(self, + request: dashboards_service.UpdateDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Replaces an existing custom dashboard with a new definition. + + This method requires the ``monitoring.dashboards.update`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (:class:`google.monitoring.dashboard_v1.types.UpdateDashboardRequest`): + The request object. The `UpdateDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.types.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + # Create or coerce a protobuf request object. + request = dashboards_service.UpdateDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_dashboard, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("dashboard.name", request.dashboard.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-monitoring-dashboard", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DashboardsServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py new file mode 100644 index 0000000..1aa9896 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py @@ -0,0 +1,663 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.monitoring.dashboard_v1.services.dashboards_service import pagers +from google.monitoring.dashboard_v1.types import dashboard +from google.monitoring.dashboard_v1.types import dashboards_service +from google.monitoring.dashboard_v1.types import layouts +from .transports.base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DashboardsServiceGrpcTransport +from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport + + +class DashboardsServiceClientMeta(type): + """Metaclass for the DashboardsService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[DashboardsServiceTransport]] + _transport_registry["grpc"] = DashboardsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DashboardsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DashboardsServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DashboardsServiceClient(metaclass=DashboardsServiceClientMeta): + """Manages Stackdriver dashboards. A dashboard is an arrangement + of data display widgets in a specific layout. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "monitoring.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DashboardsServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DashboardsServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DashboardsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DashboardsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def dashboard_path(project: str,dashboard: str,) -> str: + """Returns a fully-qualified dashboard string.""" + return "projects/{project}/dashboards/{dashboard}".format(project=project, dashboard=dashboard, ) + + @staticmethod + def parse_dashboard_path(path: str) -> Dict[str,str]: + """Parses a dashboard path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/dashboards/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DashboardsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dashboards service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, DashboardsServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DashboardsServiceTransport): + # transport is a DashboardsServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_dashboard(self, + request: dashboards_service.CreateDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Creates a new custom dashboard. For examples on how you can use + this API to create dashboards, see `Managing dashboards by + API `__. + This method requires the ``monitoring.dashboards.create`` + permission on the specified project. For more information about + permissions, see `Cloud Identity and Access + Management `__. + + Args: + request (google.monitoring.dashboard_v1.types.CreateDashboardRequest): + The request object. The `CreateDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.types.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.CreateDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.CreateDashboardRequest): + request = dashboards_service.CreateDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_dashboard] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_dashboards(self, + request: dashboards_service.ListDashboardsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDashboardsPager: + r"""Lists the existing dashboards. + + This method requires the ``monitoring.dashboards.list`` + permission on the specified project. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (google.monitoring.dashboard_v1.types.ListDashboardsRequest): + The request object. The `ListDashboards` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.services.dashboards_service.pagers.ListDashboardsPager: + The ListDashboards request. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.ListDashboardsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.ListDashboardsRequest): + request = dashboards_service.ListDashboardsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_dashboards] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDashboardsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_dashboard(self, + request: dashboards_service.GetDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Fetches a specific dashboard. + + This method requires the ``monitoring.dashboards.get`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (google.monitoring.dashboard_v1.types.GetDashboardRequest): + The request object. The `GetDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.types.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.GetDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.GetDashboardRequest): + request = dashboards_service.GetDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_dashboard] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_dashboard(self, + request: dashboards_service.DeleteDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an existing custom dashboard. + + This method requires the ``monitoring.dashboards.delete`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (google.monitoring.dashboard_v1.types.DeleteDashboardRequest): + The request object. The `DeleteDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.DeleteDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.DeleteDashboardRequest): + request = dashboards_service.DeleteDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_dashboard] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_dashboard(self, + request: dashboards_service.UpdateDashboardRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dashboard.Dashboard: + r"""Replaces an existing custom dashboard with a new definition. + + This method requires the ``monitoring.dashboards.update`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Args: + request (google.monitoring.dashboard_v1.types.UpdateDashboardRequest): + The request object. The `UpdateDashboard` request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.monitoring.dashboard_v1.types.Dashboard: + A Google Stackdriver dashboard. + Dashboards define the content and layout + of pages in the Stackdriver web + application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.UpdateDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.UpdateDashboardRequest): + request = dashboards_service.UpdateDashboardRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_dashboard] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("dashboard.name", request.dashboard.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-monitoring-dashboard", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DashboardsServiceClient", +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py new file mode 100644 index 0000000..2ec062b --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.monitoring.dashboard_v1.types import dashboard +from google.monitoring.dashboard_v1.types import dashboards_service + + +class ListDashboardsPager: + """A pager for iterating through ``list_dashboards`` requests. + + This class thinly wraps an initial + :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``dashboards`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDashboards`` requests and continue to iterate + through the ``dashboards`` field on the + corresponding responses. + + All the usual :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., dashboards_service.ListDashboardsResponse], + request: dashboards_service.ListDashboardsRequest, + response: dashboards_service.ListDashboardsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.monitoring.dashboard_v1.types.ListDashboardsRequest): + The initial request object. + response (google.monitoring.dashboard_v1.types.ListDashboardsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = dashboards_service.ListDashboardsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[dashboards_service.ListDashboardsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[dashboard.Dashboard]: + for page in self.pages: + yield from page.dashboards + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDashboardsAsyncPager: + """A pager for iterating through ``list_dashboards`` requests. + + This class thinly wraps an initial + :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``dashboards`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDashboards`` requests and continue to iterate + through the ``dashboards`` field on the + corresponding responses. + + All the usual :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[dashboards_service.ListDashboardsResponse]], + request: dashboards_service.ListDashboardsRequest, + response: dashboards_service.ListDashboardsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.monitoring.dashboard_v1.types.ListDashboardsRequest): + The initial request object. + response (google.monitoring.dashboard_v1.types.ListDashboardsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = dashboards_service.ListDashboardsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[dashboards_service.ListDashboardsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[dashboard.Dashboard]: + async def async_generator(): + async for page in self.pages: + for response in page.dashboards: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py new file mode 100644 index 0000000..2d413c9 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DashboardsServiceTransport +from .grpc import DashboardsServiceGrpcTransport +from .grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DashboardsServiceTransport]] +_transport_registry['grpc'] = DashboardsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DashboardsServiceGrpcAsyncIOTransport + +__all__ = ( + 'DashboardsServiceTransport', + 'DashboardsServiceGrpcTransport', + 'DashboardsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py new file mode 100644 index 0000000..194aaae --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.monitoring.dashboard_v1.types import dashboard +from google.monitoring.dashboard_v1.types import dashboards_service +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-monitoring-dashboard', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class DashboardsServiceTransport(abc.ABC): + """Abstract transport class for DashboardsService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ) + + DEFAULT_HOST: str = 'monitoring.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_dashboard: gapic_v1.method.wrap_method( + self.create_dashboard, + default_timeout=30.0, + client_info=client_info, + ), + self.list_dashboards: gapic_v1.method.wrap_method( + self.list_dashboards, + default_timeout=None, + client_info=client_info, + ), + self.get_dashboard: gapic_v1.method.wrap_method( + self.get_dashboard, + default_timeout=None, + client_info=client_info, + ), + self.delete_dashboard: gapic_v1.method.wrap_method( + self.delete_dashboard, + default_timeout=30.0, + client_info=client_info, + ), + self.update_dashboard: gapic_v1.method.wrap_method( + self.update_dashboard, + default_timeout=30.0, + client_info=client_info, + ), + } + + @property + def create_dashboard(self) -> Callable[ + [dashboards_service.CreateDashboardRequest], + Union[ + dashboard.Dashboard, + Awaitable[dashboard.Dashboard] + ]]: + raise NotImplementedError() + + @property + def list_dashboards(self) -> Callable[ + [dashboards_service.ListDashboardsRequest], + Union[ + dashboards_service.ListDashboardsResponse, + Awaitable[dashboards_service.ListDashboardsResponse] + ]]: + raise NotImplementedError() + + @property + def get_dashboard(self) -> Callable[ + [dashboards_service.GetDashboardRequest], + Union[ + dashboard.Dashboard, + Awaitable[dashboard.Dashboard] + ]]: + raise NotImplementedError() + + @property + def delete_dashboard(self) -> Callable[ + [dashboards_service.DeleteDashboardRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_dashboard(self) -> Callable[ + [dashboards_service.UpdateDashboardRequest], + Union[ + dashboard.Dashboard, + Awaitable[dashboard.Dashboard] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DashboardsServiceTransport', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py new file mode 100644 index 0000000..cb50a85 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py @@ -0,0 +1,382 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.monitoring.dashboard_v1.types import dashboard +from google.monitoring.dashboard_v1.types import dashboards_service +from google.protobuf import empty_pb2 # type: ignore +from .base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO + + +class DashboardsServiceGrpcTransport(DashboardsServiceTransport): + """gRPC backend transport for DashboardsService. + + Manages Stackdriver dashboards. A dashboard is an arrangement + of data display widgets in a specific layout. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'monitoring.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'monitoring.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_dashboard(self) -> Callable[ + [dashboards_service.CreateDashboardRequest], + dashboard.Dashboard]: + r"""Return a callable for the create dashboard method over gRPC. + + Creates a new custom dashboard. For examples on how you can use + this API to create dashboards, see `Managing dashboards by + API `__. + This method requires the ``monitoring.dashboards.create`` + permission on the specified project. For more information about + permissions, see `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.CreateDashboardRequest], + ~.Dashboard]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_dashboard' not in self._stubs: + self._stubs['create_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard', + request_serializer=dashboards_service.CreateDashboardRequest.serialize, + response_deserializer=dashboard.Dashboard.deserialize, + ) + return self._stubs['create_dashboard'] + + @property + def list_dashboards(self) -> Callable[ + [dashboards_service.ListDashboardsRequest], + dashboards_service.ListDashboardsResponse]: + r"""Return a callable for the list dashboards method over gRPC. + + Lists the existing dashboards. + + This method requires the ``monitoring.dashboards.list`` + permission on the specified project. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.ListDashboardsRequest], + ~.ListDashboardsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_dashboards' not in self._stubs: + self._stubs['list_dashboards'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/ListDashboards', + request_serializer=dashboards_service.ListDashboardsRequest.serialize, + response_deserializer=dashboards_service.ListDashboardsResponse.deserialize, + ) + return self._stubs['list_dashboards'] + + @property + def get_dashboard(self) -> Callable[ + [dashboards_service.GetDashboardRequest], + dashboard.Dashboard]: + r"""Return a callable for the get dashboard method over gRPC. + + Fetches a specific dashboard. + + This method requires the ``monitoring.dashboards.get`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.GetDashboardRequest], + ~.Dashboard]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_dashboard' not in self._stubs: + self._stubs['get_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/GetDashboard', + request_serializer=dashboards_service.GetDashboardRequest.serialize, + response_deserializer=dashboard.Dashboard.deserialize, + ) + return self._stubs['get_dashboard'] + + @property + def delete_dashboard(self) -> Callable[ + [dashboards_service.DeleteDashboardRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete dashboard method over gRPC. + + Deletes an existing custom dashboard. + + This method requires the ``monitoring.dashboards.delete`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.DeleteDashboardRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_dashboard' not in self._stubs: + self._stubs['delete_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard', + request_serializer=dashboards_service.DeleteDashboardRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_dashboard'] + + @property + def update_dashboard(self) -> Callable[ + [dashboards_service.UpdateDashboardRequest], + dashboard.Dashboard]: + r"""Return a callable for the update dashboard method over gRPC. + + Replaces an existing custom dashboard with a new definition. + + This method requires the ``monitoring.dashboards.update`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.UpdateDashboardRequest], + ~.Dashboard]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_dashboard' not in self._stubs: + self._stubs['update_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard', + request_serializer=dashboards_service.UpdateDashboardRequest.serialize, + response_deserializer=dashboard.Dashboard.deserialize, + ) + return self._stubs['update_dashboard'] + + +__all__ = ( + 'DashboardsServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..fadb181 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py @@ -0,0 +1,386 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.monitoring.dashboard_v1.types import dashboard +from google.monitoring.dashboard_v1.types import dashboards_service +from google.protobuf import empty_pb2 # type: ignore +from .base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DashboardsServiceGrpcTransport + + +class DashboardsServiceGrpcAsyncIOTransport(DashboardsServiceTransport): + """gRPC AsyncIO backend transport for DashboardsService. + + Manages Stackdriver dashboards. A dashboard is an arrangement + of data display widgets in a specific layout. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'monitoring.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'monitoring.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_dashboard(self) -> Callable[ + [dashboards_service.CreateDashboardRequest], + Awaitable[dashboard.Dashboard]]: + r"""Return a callable for the create dashboard method over gRPC. + + Creates a new custom dashboard. For examples on how you can use + this API to create dashboards, see `Managing dashboards by + API `__. + This method requires the ``monitoring.dashboards.create`` + permission on the specified project. For more information about + permissions, see `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.CreateDashboardRequest], + Awaitable[~.Dashboard]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_dashboard' not in self._stubs: + self._stubs['create_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard', + request_serializer=dashboards_service.CreateDashboardRequest.serialize, + response_deserializer=dashboard.Dashboard.deserialize, + ) + return self._stubs['create_dashboard'] + + @property + def list_dashboards(self) -> Callable[ + [dashboards_service.ListDashboardsRequest], + Awaitable[dashboards_service.ListDashboardsResponse]]: + r"""Return a callable for the list dashboards method over gRPC. + + Lists the existing dashboards. + + This method requires the ``monitoring.dashboards.list`` + permission on the specified project. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.ListDashboardsRequest], + Awaitable[~.ListDashboardsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_dashboards' not in self._stubs: + self._stubs['list_dashboards'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/ListDashboards', + request_serializer=dashboards_service.ListDashboardsRequest.serialize, + response_deserializer=dashboards_service.ListDashboardsResponse.deserialize, + ) + return self._stubs['list_dashboards'] + + @property + def get_dashboard(self) -> Callable[ + [dashboards_service.GetDashboardRequest], + Awaitable[dashboard.Dashboard]]: + r"""Return a callable for the get dashboard method over gRPC. + + Fetches a specific dashboard. + + This method requires the ``monitoring.dashboards.get`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.GetDashboardRequest], + Awaitable[~.Dashboard]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_dashboard' not in self._stubs: + self._stubs['get_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/GetDashboard', + request_serializer=dashboards_service.GetDashboardRequest.serialize, + response_deserializer=dashboard.Dashboard.deserialize, + ) + return self._stubs['get_dashboard'] + + @property + def delete_dashboard(self) -> Callable[ + [dashboards_service.DeleteDashboardRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete dashboard method over gRPC. + + Deletes an existing custom dashboard. + + This method requires the ``monitoring.dashboards.delete`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.DeleteDashboardRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_dashboard' not in self._stubs: + self._stubs['delete_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard', + request_serializer=dashboards_service.DeleteDashboardRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_dashboard'] + + @property + def update_dashboard(self) -> Callable[ + [dashboards_service.UpdateDashboardRequest], + Awaitable[dashboard.Dashboard]]: + r"""Return a callable for the update dashboard method over gRPC. + + Replaces an existing custom dashboard with a new definition. + + This method requires the ``monitoring.dashboards.update`` + permission on the specified dashboard. For more information, see + `Cloud Identity and Access + Management `__. + + Returns: + Callable[[~.UpdateDashboardRequest], + Awaitable[~.Dashboard]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_dashboard' not in self._stubs: + self._stubs['update_dashboard'] = self.grpc_channel.unary_unary( + '/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard', + request_serializer=dashboards_service.UpdateDashboardRequest.serialize, + response_deserializer=dashboard.Dashboard.deserialize, + ) + return self._stubs['update_dashboard'] + + +__all__ = ( + 'DashboardsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py new file mode 100644 index 0000000..eca1b1c --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .common import ( + Aggregation, + PickTimeSeriesFilter, + StatisticalTimeSeriesFilter, +) +from .dashboard import ( + Dashboard, +) +from .dashboards_service import ( + CreateDashboardRequest, + DeleteDashboardRequest, + GetDashboardRequest, + ListDashboardsRequest, + ListDashboardsResponse, + UpdateDashboardRequest, +) +from .layouts import ( + ColumnLayout, + GridLayout, + MosaicLayout, + RowLayout, +) +from .metrics import ( + Threshold, + TimeSeriesFilter, + TimeSeriesFilterRatio, + TimeSeriesQuery, + SparkChartType, +) +from .scorecard import ( + Scorecard, +) +from .text import ( + Text, +) +from .widget import ( + Widget, +) +from .xychart import ( + ChartOptions, + XyChart, +) + +__all__ = ( + 'Aggregation', + 'PickTimeSeriesFilter', + 'StatisticalTimeSeriesFilter', + 'Dashboard', + 'CreateDashboardRequest', + 'DeleteDashboardRequest', + 'GetDashboardRequest', + 'ListDashboardsRequest', + 'ListDashboardsResponse', + 'UpdateDashboardRequest', + 'ColumnLayout', + 'GridLayout', + 'MosaicLayout', + 'RowLayout', + 'Threshold', + 'TimeSeriesFilter', + 'TimeSeriesFilterRatio', + 'TimeSeriesQuery', + 'SparkChartType', + 'Scorecard', + 'Text', + 'Widget', + 'ChartOptions', + 'XyChart', +) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py new file mode 100644 index 0000000..f686374 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'Aggregation', + 'PickTimeSeriesFilter', + 'StatisticalTimeSeriesFilter', + }, +) + + +class Aggregation(proto.Message): + r"""Describes how to combine multiple time series to provide a different + view of the data. Aggregation of time series is done in two steps. + First, each time series in the set is *aligned* to the same time + interval boundaries, then the set of time series is optionally + *reduced* in number. + + Alignment consists of applying the ``per_series_aligner`` operation + to each time series after its data has been divided into regular + ``alignment_period`` time intervals. This process takes *all* of the + data points in an alignment period, applies a mathematical + transformation such as averaging, minimum, maximum, delta, etc., and + converts them into a single data point per period. + + Reduction is when the aligned and transformed time series can + optionally be combined, reducing the number of time series through + similar mathematical transformations. Reduction involves applying a + ``cross_series_reducer`` to all the time series, optionally sorting + the time series into subsets with ``group_by_fields``, and applying + the reducer to each subset. + + The raw time series data can contain a huge amount of information + from multiple sources. Alignment and reduction transforms this mass + of data into a more manageable and representative collection of + data, for example "the 95% latency across the average of all tasks + in a cluster". This representative data can be more easily graphed + and comprehended, and the individual time series data is still + available for later drilldown. For more details, see `Filtering and + aggregation `__. + + Attributes: + alignment_period (google.protobuf.duration_pb2.Duration): + The ``alignment_period`` specifies a time interval, in + seconds, that is used to divide the data in all the [time + series][google.monitoring.v3.TimeSeries] into consistent + blocks of time. This will be done before the per-series + aligner can be applied to the data. + + The value must be at least 60 seconds. If a per-series + aligner other than ``ALIGN_NONE`` is specified, this field + is required or an error is returned. If no per-series + aligner is specified, or the aligner ``ALIGN_NONE`` is + specified, then this field is ignored. + + The maximum value of the ``alignment_period`` is 2 years, or + 104 weeks. + per_series_aligner (google.monitoring.dashboard_v1.types.Aggregation.Aligner): + An ``Aligner`` describes how to bring the data points in a + single time series into temporal alignment. Except for + ``ALIGN_NONE``, all alignments cause all the data points in + an ``alignment_period`` to be mathematically grouped + together, resulting in a single data point for each + ``alignment_period`` with end timestamp at the end of the + period. + + Not all alignment operations may be applied to all time + series. The valid choices depend on the ``metric_kind`` and + ``value_type`` of the original time series. Alignment can + change the ``metric_kind`` or the ``value_type`` of the time + series. + + Time series data must be aligned in order to perform + cross-time series reduction. If ``cross_series_reducer`` is + specified, then ``per_series_aligner`` must be specified and + not equal to ``ALIGN_NONE`` and ``alignment_period`` must be + specified; otherwise, an error is returned. + cross_series_reducer (google.monitoring.dashboard_v1.types.Aggregation.Reducer): + The reduction operation to be used to combine time series + into a single time series, where the value of each data + point in the resulting series is a function of all the + already aligned values in the input time series. + + Not all reducer operations can be applied to all time + series. The valid choices depend on the ``metric_kind`` and + the ``value_type`` of the original time series. Reduction + can yield a time series with a different ``metric_kind`` or + ``value_type`` than the input time series. + + Time series data must first be aligned (see + ``per_series_aligner``) in order to perform cross-time + series reduction. If ``cross_series_reducer`` is specified, + then ``per_series_aligner`` must be specified, and must not + be ``ALIGN_NONE``. An ``alignment_period`` must also be + specified; otherwise, an error is returned. + group_by_fields (Sequence[str]): + The set of fields to preserve when ``cross_series_reducer`` + is specified. The ``group_by_fields`` determine how the time + series are partitioned into subsets prior to applying the + aggregation operation. Each subset contains time series that + have the same value for each of the grouping fields. Each + individual time series is a member of exactly one subset. + The ``cross_series_reducer`` is applied to each subset of + time series. It is not possible to reduce across different + resource types, so this field implicitly contains + ``resource.type``. Fields not specified in + ``group_by_fields`` are aggregated away. If + ``group_by_fields`` is not specified and all the time series + have the same resource type, then the time series are + aggregated into a single output time series. If + ``cross_series_reducer`` is not defined, this field is + ignored. + """ + class Aligner(proto.Enum): + r"""The ``Aligner`` specifies the operation that will be applied to the + data points in each alignment period in a time series. Except for + ``ALIGN_NONE``, which specifies that no operation be applied, each + alignment operation replaces the set of data values in each + alignment period with a single value: the result of applying the + operation to the data values. An aligned time series has a single + data value at the end of each ``alignment_period``. + + An alignment operation can change the data type of the values, too. + For example, if you apply a counting operation to boolean values, + the data ``value_type`` in the original time series is ``BOOLEAN``, + but the ``value_type`` in the aligned result is ``INT64``. + """ + ALIGN_NONE = 0 + ALIGN_DELTA = 1 + ALIGN_RATE = 2 + ALIGN_INTERPOLATE = 3 + ALIGN_NEXT_OLDER = 4 + ALIGN_MIN = 10 + ALIGN_MAX = 11 + ALIGN_MEAN = 12 + ALIGN_COUNT = 13 + ALIGN_SUM = 14 + ALIGN_STDDEV = 15 + ALIGN_COUNT_TRUE = 16 + ALIGN_COUNT_FALSE = 24 + ALIGN_FRACTION_TRUE = 17 + ALIGN_PERCENTILE_99 = 18 + ALIGN_PERCENTILE_95 = 19 + ALIGN_PERCENTILE_50 = 20 + ALIGN_PERCENTILE_05 = 21 + ALIGN_PERCENT_CHANGE = 23 + + class Reducer(proto.Enum): + r"""A Reducer operation describes how to aggregate data points + from multiple time series into a single time series, where the + value of each data point in the resulting series is a function + of all the already aligned values in the input time series. + """ + REDUCE_NONE = 0 + REDUCE_MEAN = 1 + REDUCE_MIN = 2 + REDUCE_MAX = 3 + REDUCE_SUM = 4 + REDUCE_STDDEV = 5 + REDUCE_COUNT = 6 + REDUCE_COUNT_TRUE = 7 + REDUCE_COUNT_FALSE = 15 + REDUCE_FRACTION_TRUE = 8 + REDUCE_PERCENTILE_99 = 9 + REDUCE_PERCENTILE_95 = 10 + REDUCE_PERCENTILE_50 = 11 + REDUCE_PERCENTILE_05 = 12 + + alignment_period = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + per_series_aligner = proto.Field( + proto.ENUM, + number=2, + enum=Aligner, + ) + cross_series_reducer = proto.Field( + proto.ENUM, + number=4, + enum=Reducer, + ) + group_by_fields = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class PickTimeSeriesFilter(proto.Message): + r"""Describes a ranking-based time series filter. Each input time series + is ranked with an aligner. The filter will allow up to + ``num_time_series`` time series to pass through it, selecting them + based on the relative ranking. + + For example, if ``ranking_method`` is + ``METHOD_MEAN``,\ ``direction`` is ``BOTTOM``, and + ``num_time_series`` is 3, then the 3 times series with the lowest + mean values will pass through the filter. + + Attributes: + ranking_method (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter.Method): + ``ranking_method`` is applied to each time series + independently to produce the value which will be used to + compare the time series to other time series. + num_time_series (int): + How many time series to allow to pass through + the filter. + direction (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter.Direction): + How to use the ranking to select time series + that pass through the filter. + """ + class Method(proto.Enum): + r"""The value reducers that can be applied to a + ``PickTimeSeriesFilter``. + """ + METHOD_UNSPECIFIED = 0 + METHOD_MEAN = 1 + METHOD_MAX = 2 + METHOD_MIN = 3 + METHOD_SUM = 4 + METHOD_LATEST = 5 + + class Direction(proto.Enum): + r"""Describes the ranking directions.""" + DIRECTION_UNSPECIFIED = 0 + TOP = 1 + BOTTOM = 2 + + ranking_method = proto.Field( + proto.ENUM, + number=1, + enum=Method, + ) + num_time_series = proto.Field( + proto.INT32, + number=2, + ) + direction = proto.Field( + proto.ENUM, + number=3, + enum=Direction, + ) + + +class StatisticalTimeSeriesFilter(proto.Message): + r"""A filter that ranks streams based on their statistical + relation to other streams in a request. + Note: This field is deprecated and completely ignored by the + API. + + Attributes: + ranking_method (google.monitoring.dashboard_v1.types.StatisticalTimeSeriesFilter.Method): + ``rankingMethod`` is applied to a set of time series, and + then the produced value for each individual time series is + used to compare a given time series to others. These are + methods that cannot be applied stream-by-stream, but rather + require the full context of a request to evaluate time + series. + num_time_series (int): + How many time series to output. + """ + class Method(proto.Enum): + r"""The filter methods that can be applied to a stream.""" + METHOD_UNSPECIFIED = 0 + METHOD_CLUSTER_OUTLIER = 1 + + ranking_method = proto.Field( + proto.ENUM, + number=1, + enum=Method, + ) + num_time_series = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py new file mode 100644 index 0000000..5ec2395 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.monitoring.dashboard_v1.types import layouts + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'Dashboard', + }, +) + + +class Dashboard(proto.Message): + r"""A Google Stackdriver dashboard. Dashboards define the content + and layout of pages in the Stackdriver web application. + + Attributes: + name (str): + Immutable. The resource name of the + dashboard. + display_name (str): + Required. The mutable, human-readable name. + etag (str): + ``etag`` is used for optimistic concurrency control as a way + to help prevent simultaneous updates of a policy from + overwriting each other. An ``etag`` is returned in the + response to ``GetDashboard``, and users are expected to put + that etag in the request to ``UpdateDashboard`` to ensure + that their change will be applied to the same version of the + Dashboard configuration. The field should not be passed + during dashboard creation. + grid_layout (google.monitoring.dashboard_v1.types.GridLayout): + Content is arranged with a basic layout that + re-flows a simple list of informational elements + like widgets or tiles. + mosaic_layout (google.monitoring.dashboard_v1.types.MosaicLayout): + The content is arranged as a grid of tiles, + with each content widget occupying one or more + grid blocks. + row_layout (google.monitoring.dashboard_v1.types.RowLayout): + The content is divided into equally spaced + rows and the widgets are arranged horizontally. + column_layout (google.monitoring.dashboard_v1.types.ColumnLayout): + The content is divided into equally spaced + columns and the widgets are arranged vertically. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + etag = proto.Field( + proto.STRING, + number=4, + ) + grid_layout = proto.Field( + proto.MESSAGE, + number=5, + oneof='layout', + message=layouts.GridLayout, + ) + mosaic_layout = proto.Field( + proto.MESSAGE, + number=6, + oneof='layout', + message=layouts.MosaicLayout, + ) + row_layout = proto.Field( + proto.MESSAGE, + number=8, + oneof='layout', + message=layouts.RowLayout, + ) + column_layout = proto.Field( + proto.MESSAGE, + number=9, + oneof='layout', + message=layouts.ColumnLayout, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py new file mode 100644 index 0000000..4cf415e --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.monitoring.dashboard_v1.types import dashboard as gmd_dashboard + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'CreateDashboardRequest', + 'ListDashboardsRequest', + 'ListDashboardsResponse', + 'GetDashboardRequest', + 'DeleteDashboardRequest', + 'UpdateDashboardRequest', + }, +) + + +class CreateDashboardRequest(proto.Message): + r"""The ``CreateDashboard`` request. + Attributes: + parent (str): + Required. The project on which to execute the request. The + format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + + The ``[PROJECT_ID_OR_NUMBER]`` must match the dashboard + resource name. + dashboard (google.monitoring.dashboard_v1.types.Dashboard): + Required. The initial dashboard + specification. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + dashboard = proto.Field( + proto.MESSAGE, + number=2, + message=gmd_dashboard.Dashboard, + ) + + +class ListDashboardsRequest(proto.Message): + r"""The ``ListDashboards`` request. + Attributes: + parent (str): + Required. The scope of the dashboards to list. The format + is: + + :: + + projects/[PROJECT_ID_OR_NUMBER] + page_size (int): + A positive number that is the maximum number + of results to return. If unspecified, a default + of 1000 is used. + page_token (str): + If this field is not empty then it must contain the + ``nextPageToken`` value returned by a previous call to this + method. Using this field causes the method to return + additional results from the previous method call. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDashboardsResponse(proto.Message): + r"""The ``ListDashboards`` request. + Attributes: + dashboards (Sequence[google.monitoring.dashboard_v1.types.Dashboard]): + The list of requested dashboards. + next_page_token (str): + If there are more results than have been returned, then this + field is set to a non-empty value. To see the additional + results, use that value as ``page_token`` in the next call + to this method. + """ + + @property + def raw_page(self): + return self + + dashboards = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gmd_dashboard.Dashboard, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDashboardRequest(proto.Message): + r"""The ``GetDashboard`` request. + Attributes: + name (str): + Required. The resource name of the Dashboard. The format is + one of: + + - ``dashboards/[DASHBOARD_ID]`` (for system dashboards) + - ``projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID]`` + (for custom dashboards). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteDashboardRequest(proto.Message): + r"""The ``DeleteDashboard`` request. + Attributes: + name (str): + Required. The resource name of the Dashboard. The format is: + + :: + + projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID] + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDashboardRequest(proto.Message): + r"""The ``UpdateDashboard`` request. + Attributes: + dashboard (google.monitoring.dashboard_v1.types.Dashboard): + Required. The dashboard that will replace the + existing dashboard. + """ + + dashboard = proto.Field( + proto.MESSAGE, + number=1, + message=gmd_dashboard.Dashboard, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py new file mode 100644 index 0000000..041e5fd --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py new file mode 100644 index 0000000..1ea90ce --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.monitoring.dashboard_v1.types import widget as gmd_widget + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'GridLayout', + 'MosaicLayout', + 'RowLayout', + 'ColumnLayout', + }, +) + + +class GridLayout(proto.Message): + r"""A basic layout divides the available space into vertical + columns of equal width and arranges a list of widgets using a + row-first strategy. + + Attributes: + columns (int): + The number of columns into which the view's + width is divided. If omitted or set to zero, a + system default will be used while rendering. + widgets (Sequence[google.monitoring.dashboard_v1.types.Widget]): + The informational elements that are arranged + into the columns row-first. + """ + + columns = proto.Field( + proto.INT64, + number=1, + ) + widgets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gmd_widget.Widget, + ) + + +class MosaicLayout(proto.Message): + r"""A mosaic layout divides the available space into a grid of blocks, + and overlays the grid with tiles. Unlike ``GridLayout``, tiles may + span multiple grid blocks and can be placed at arbitrary locations + in the grid. + + Attributes: + columns (int): + The number of columns in the mosaic grid. The + number of columns must be between 1 and 12, + inclusive. + tiles (Sequence[google.monitoring.dashboard_v1.types.MosaicLayout.Tile]): + The tiles to display. + """ + + class Tile(proto.Message): + r"""A single tile in the mosaic. The placement and size of the + tile are configurable. + + Attributes: + x_pos (int): + The zero-indexed position of the tile in grid blocks + relative to the left edge of the grid. Tiles must be + contained within the specified number of columns. ``x_pos`` + cannot be negative. + y_pos (int): + The zero-indexed position of the tile in grid blocks + relative to the top edge of the grid. ``y_pos`` cannot be + negative. + width (int): + The width of the tile, measured in grid + blocks. Tiles must have a minimum width of 1. + height (int): + The height of the tile, measured in grid + blocks. Tiles must have a minimum height of 1. + widget (google.monitoring.dashboard_v1.types.Widget): + The informational widget contained in the tile. For example + an ``XyChart``. + """ + + x_pos = proto.Field( + proto.INT32, + number=1, + ) + y_pos = proto.Field( + proto.INT32, + number=2, + ) + width = proto.Field( + proto.INT32, + number=3, + ) + height = proto.Field( + proto.INT32, + number=4, + ) + widget = proto.Field( + proto.MESSAGE, + number=5, + message=gmd_widget.Widget, + ) + + columns = proto.Field( + proto.INT32, + number=1, + ) + tiles = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Tile, + ) + + +class RowLayout(proto.Message): + r"""A simplified layout that divides the available space into + rows and arranges a set of widgets horizontally in each row. + + Attributes: + rows (Sequence[google.monitoring.dashboard_v1.types.RowLayout.Row]): + The rows of content to display. + """ + + class Row(proto.Message): + r"""Defines the layout properties and content for a row. + Attributes: + weight (int): + The relative weight of this row. The row + weight is used to adjust the height of rows on + the screen (relative to peers). Greater the + weight, greater the height of the row on the + screen. If omitted, a value of 1 is used while + rendering. + widgets (Sequence[google.monitoring.dashboard_v1.types.Widget]): + The display widgets arranged horizontally in + this row. + """ + + weight = proto.Field( + proto.INT64, + number=1, + ) + widgets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gmd_widget.Widget, + ) + + rows = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Row, + ) + + +class ColumnLayout(proto.Message): + r"""A simplified layout that divides the available space into + vertical columns and arranges a set of widgets vertically in + each column. + + Attributes: + columns (Sequence[google.monitoring.dashboard_v1.types.ColumnLayout.Column]): + The columns of content to display. + """ + + class Column(proto.Message): + r"""Defines the layout properties and content for a column. + Attributes: + weight (int): + The relative weight of this column. The + column weight is used to adjust the width of + columns on the screen (relative to peers). + Greater the weight, greater the width of the + column on the screen. If omitted, a value of 1 + is used while rendering. + widgets (Sequence[google.monitoring.dashboard_v1.types.Widget]): + The display widgets arranged vertically in + this column. + """ + + weight = proto.Field( + proto.INT64, + number=1, + ) + widgets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gmd_widget.Widget, + ) + + columns = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Column, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py new file mode 100644 index 0000000..f37f64e --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.monitoring.dashboard_v1.types import common + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'SparkChartType', + 'TimeSeriesQuery', + 'TimeSeriesFilter', + 'TimeSeriesFilterRatio', + 'Threshold', + }, +) + + +class SparkChartType(proto.Enum): + r"""Defines the possible types of spark chart supported by the + ``Scorecard``. + """ + SPARK_CHART_TYPE_UNSPECIFIED = 0 + SPARK_LINE = 1 + SPARK_BAR = 2 + + +class TimeSeriesQuery(proto.Message): + r"""TimeSeriesQuery collects the set of supported methods for + querying time series data from the Stackdriver metrics API. + + Attributes: + time_series_filter (google.monitoring.dashboard_v1.types.TimeSeriesFilter): + Filter parameters to fetch time series. + time_series_filter_ratio (google.monitoring.dashboard_v1.types.TimeSeriesFilterRatio): + Parameters to fetch a ratio between two time + series filters. + time_series_query_language (str): + A query used to fetch time series. + unit_override (str): + The unit of data contained in fetched time series. If + non-empty, this unit will override any unit that accompanies + fetched data. The format is the same as the + ```unit`` `__ + field in ``MetricDescriptor``. + """ + + time_series_filter = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='TimeSeriesFilter', + ) + time_series_filter_ratio = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='TimeSeriesFilterRatio', + ) + time_series_query_language = proto.Field( + proto.STRING, + number=3, + oneof='source', + ) + unit_override = proto.Field( + proto.STRING, + number=5, + ) + + +class TimeSeriesFilter(proto.Message): + r"""A filter that defines a subset of time series data that is displayed + in a widget. Time series data is fetched using the + ```ListTimeSeries`` `__ + method. + + Attributes: + filter (str): + Required. The `monitoring + filter `__ + that identifies the metric types, resources, and projects to + query. + aggregation (google.monitoring.dashboard_v1.types.Aggregation): + By default, the raw time series data is + returned. Use this field to combine multiple + time series for different views of the data. + secondary_aggregation (google.monitoring.dashboard_v1.types.Aggregation): + Apply a second aggregation after ``aggregation`` is applied. + pick_time_series_filter (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter): + Ranking based time series filter. + statistical_time_series_filter (google.monitoring.dashboard_v1.types.StatisticalTimeSeriesFilter): + Statistics based time series filter. + Note: This field is deprecated and completely + ignored by the API. + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + aggregation = proto.Field( + proto.MESSAGE, + number=2, + message=common.Aggregation, + ) + secondary_aggregation = proto.Field( + proto.MESSAGE, + number=3, + message=common.Aggregation, + ) + pick_time_series_filter = proto.Field( + proto.MESSAGE, + number=4, + oneof='output_filter', + message=common.PickTimeSeriesFilter, + ) + statistical_time_series_filter = proto.Field( + proto.MESSAGE, + number=5, + oneof='output_filter', + message=common.StatisticalTimeSeriesFilter, + ) + + +class TimeSeriesFilterRatio(proto.Message): + r"""A pair of time series filters that define a ratio + computation. The output time series is the pair-wise division of + each aligned element from the numerator and denominator time + series. + + Attributes: + numerator (google.monitoring.dashboard_v1.types.TimeSeriesFilterRatio.RatioPart): + The numerator of the ratio. + denominator (google.monitoring.dashboard_v1.types.TimeSeriesFilterRatio.RatioPart): + The denominator of the ratio. + secondary_aggregation (google.monitoring.dashboard_v1.types.Aggregation): + Apply a second aggregation after the ratio is + computed. + pick_time_series_filter (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter): + Ranking based time series filter. + statistical_time_series_filter (google.monitoring.dashboard_v1.types.StatisticalTimeSeriesFilter): + Statistics based time series filter. + Note: This field is deprecated and completely + ignored by the API. + """ + + class RatioPart(proto.Message): + r"""Describes a query to build the numerator or denominator of a + TimeSeriesFilterRatio. + + Attributes: + filter (str): + Required. The `monitoring + filter `__ + that identifies the metric types, resources, and projects to + query. + aggregation (google.monitoring.dashboard_v1.types.Aggregation): + By default, the raw time series data is + returned. Use this field to combine multiple + time series for different views of the data. + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + aggregation = proto.Field( + proto.MESSAGE, + number=2, + message=common.Aggregation, + ) + + numerator = proto.Field( + proto.MESSAGE, + number=1, + message=RatioPart, + ) + denominator = proto.Field( + proto.MESSAGE, + number=2, + message=RatioPart, + ) + secondary_aggregation = proto.Field( + proto.MESSAGE, + number=3, + message=common.Aggregation, + ) + pick_time_series_filter = proto.Field( + proto.MESSAGE, + number=4, + oneof='output_filter', + message=common.PickTimeSeriesFilter, + ) + statistical_time_series_filter = proto.Field( + proto.MESSAGE, + number=5, + oneof='output_filter', + message=common.StatisticalTimeSeriesFilter, + ) + + +class Threshold(proto.Message): + r"""Defines a threshold for categorizing time series values. + Attributes: + label (str): + A label for the threshold. + value (float): + The value of the threshold. The value should + be defined in the native scale of the metric. + color (google.monitoring.dashboard_v1.types.Threshold.Color): + The state color for this threshold. Color is + not allowed in a XyChart. + direction (google.monitoring.dashboard_v1.types.Threshold.Direction): + The direction for the current threshold. + Direction is not allowed in a XyChart. + """ + class Color(proto.Enum): + r"""The color suggests an interpretation to the viewer when + actual values cross the threshold. Comments on each color + provide UX guidance on how users can be expected to interpret a + given state color. + """ + COLOR_UNSPECIFIED = 0 + YELLOW = 4 + RED = 6 + + class Direction(proto.Enum): + r"""Whether the threshold is considered crossed by an actual + value above or below its threshold value. + """ + DIRECTION_UNSPECIFIED = 0 + ABOVE = 1 + BELOW = 2 + + label = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.DOUBLE, + number=2, + ) + color = proto.Field( + proto.ENUM, + number=3, + enum=Color, + ) + direction = proto.Field( + proto.ENUM, + number=4, + enum=Direction, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py new file mode 100644 index 0000000..c0fcd23 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.monitoring.dashboard_v1.types import metrics +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'Scorecard', + }, +) + + +class Scorecard(proto.Message): + r"""A widget showing the latest value of a metric, and how this + value relates to one or more thresholds. + + Attributes: + time_series_query (google.monitoring.dashboard_v1.types.TimeSeriesQuery): + Required. Fields for querying time series + data from the Stackdriver metrics API. + gauge_view (google.monitoring.dashboard_v1.types.Scorecard.GaugeView): + Will cause the scorecard to show a gauge + chart. + spark_chart_view (google.monitoring.dashboard_v1.types.Scorecard.SparkChartView): + Will cause the scorecard to show a spark + chart. + thresholds (Sequence[google.monitoring.dashboard_v1.types.Threshold]): + The thresholds used to determine the state of + the scorecard given the time series' current + value. For an actual value x, the scorecard is + in a danger state if x is less than or equal to + a danger threshold that triggers below, or + greater than or equal to a danger threshold that + triggers above. Similarly, if x is above/below a + warning threshold that triggers above/below, + then the scorecard is in a warning state - + unless x also puts it in a danger state. (Danger + trumps warning.) + As an example, consider a scorecard with the + following four thresholds: { + value: 90, + category: 'DANGER', + trigger: 'ABOVE', + }, + { + value: 70, + category: 'WARNING', + trigger: 'ABOVE', + }, + { + value: 10, + category: 'DANGER', + trigger: 'BELOW', + }, + { + value: 20, + category: 'WARNING', + trigger: 'BELOW', + } + + Then: values less than or equal to 10 would put + the scorecard in a DANGER state, values greater + than 10 but less than or equal to 20 a WARNING + state, values strictly between 20 and 70 an OK + state, values greater than or equal to 70 but + less than 90 a WARNING state, and values greater + than or equal to 90 a DANGER state. + """ + + class GaugeView(proto.Message): + r"""A gauge chart shows where the current value sits within a + pre-defined range. The upper and lower bounds should define the + possible range of values for the scorecard's query (inclusive). + + Attributes: + lower_bound (float): + The lower bound for this gauge chart. The + value of the chart should always be greater than + or equal to this. + upper_bound (float): + The upper bound for this gauge chart. The + value of the chart should always be less than or + equal to this. + """ + + lower_bound = proto.Field( + proto.DOUBLE, + number=1, + ) + upper_bound = proto.Field( + proto.DOUBLE, + number=2, + ) + + class SparkChartView(proto.Message): + r"""A sparkChart is a small chart suitable for inclusion in a + table-cell or inline in text. This message contains the + configuration for a sparkChart to show up on a Scorecard, + showing recent trends of the scorecard's timeseries. + + Attributes: + spark_chart_type (google.monitoring.dashboard_v1.types.SparkChartType): + Required. The type of sparkchart to show in + this chartView. + min_alignment_period (google.protobuf.duration_pb2.Duration): + The lower bound on data point frequency in + the chart implemented by specifying the minimum + alignment period to use in a time series query. + For example, if the data is published once every + 10 minutes it would not make sense to fetch and + align data at one minute intervals. This field + is optional and exists only as a hint. + """ + + spark_chart_type = proto.Field( + proto.ENUM, + number=1, + enum=metrics.SparkChartType, + ) + min_alignment_period = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + time_series_query = proto.Field( + proto.MESSAGE, + number=1, + message=metrics.TimeSeriesQuery, + ) + gauge_view = proto.Field( + proto.MESSAGE, + number=4, + oneof='data_view', + message=GaugeView, + ) + spark_chart_view = proto.Field( + proto.MESSAGE, + number=5, + oneof='data_view', + message=SparkChartView, + ) + thresholds = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=metrics.Threshold, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py new file mode 100644 index 0000000..041e5fd --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py new file mode 100644 index 0000000..031f733 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'Text', + }, +) + + +class Text(proto.Message): + r"""A widget that displays textual content. + Attributes: + content (str): + The text content to be displayed. + format_ (google.monitoring.dashboard_v1.types.Text.Format): + How the text content is formatted. + """ + class Format(proto.Enum): + r"""The format type of the text content.""" + FORMAT_UNSPECIFIED = 0 + MARKDOWN = 1 + RAW = 2 + + content = proto.Field( + proto.STRING, + number=1, + ) + format_ = proto.Field( + proto.ENUM, + number=2, + enum=Format, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py new file mode 100644 index 0000000..15a957c --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.monitoring.dashboard_v1.types import scorecard as gmd_scorecard +from google.monitoring.dashboard_v1.types import text as gmd_text +from google.monitoring.dashboard_v1.types import xychart +from google.protobuf import empty_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'Widget', + }, +) + + +class Widget(proto.Message): + r"""Widget contains a single dashboard component and + configuration of how to present the component in the dashboard. + + Attributes: + title (str): + Optional. The title of the widget. + xy_chart (google.monitoring.dashboard_v1.types.XyChart): + A chart of time series data. + scorecard (google.monitoring.dashboard_v1.types.Scorecard): + A scorecard summarizing time series data. + text (google.monitoring.dashboard_v1.types.Text): + A raw string or markdown displaying textual + content. + blank (google.protobuf.empty_pb2.Empty): + A blank space. + """ + + title = proto.Field( + proto.STRING, + number=1, + ) + xy_chart = proto.Field( + proto.MESSAGE, + number=2, + oneof='content', + message=xychart.XyChart, + ) + scorecard = proto.Field( + proto.MESSAGE, + number=3, + oneof='content', + message=gmd_scorecard.Scorecard, + ) + text = proto.Field( + proto.MESSAGE, + number=4, + oneof='content', + message=gmd_text.Text, + ) + blank = proto.Field( + proto.MESSAGE, + number=5, + oneof='content', + message=empty_pb2.Empty, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py new file mode 100644 index 0000000..ddddc57 --- /dev/null +++ b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.monitoring.dashboard_v1.types import metrics +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.monitoring.dashboard.v1', + manifest={ + 'XyChart', + 'ChartOptions', + }, +) + + +class XyChart(proto.Message): + r"""A chart that displays data on a 2D (X and Y axes) plane. + Attributes: + data_sets (Sequence[google.monitoring.dashboard_v1.types.XyChart.DataSet]): + Required. The data displayed in this chart. + timeshift_duration (google.protobuf.duration_pb2.Duration): + The duration used to display a comparison + chart. A comparison chart simultaneously shows + values from two similar-length time periods + (e.g., week-over-week metrics). + The duration must be positive, and it can only + be applied to charts with data sets of LINE plot + type. + thresholds (Sequence[google.monitoring.dashboard_v1.types.Threshold]): + Threshold lines drawn horizontally across the + chart. + x_axis (google.monitoring.dashboard_v1.types.XyChart.Axis): + The properties applied to the X axis. + y_axis (google.monitoring.dashboard_v1.types.XyChart.Axis): + The properties applied to the Y axis. + chart_options (google.monitoring.dashboard_v1.types.ChartOptions): + Display options for the chart. + """ + + class DataSet(proto.Message): + r"""Groups a time series query definition with charting options. + Attributes: + time_series_query (google.monitoring.dashboard_v1.types.TimeSeriesQuery): + Required. Fields for querying time series + data from the Stackdriver metrics API. + plot_type (google.monitoring.dashboard_v1.types.XyChart.DataSet.PlotType): + How this data should be plotted on the chart. + legend_template (str): + A template string for naming ``TimeSeries`` in the resulting + data set. This should be a string with interpolations of the + form ``${label_name}``, which will resolve to the label's + value. + min_alignment_period (google.protobuf.duration_pb2.Duration): + Optional. The lower bound on data point frequency for this + data set, implemented by specifying the minimum alignment + period to use in a time series query. For example, if the + data is published once every 10 minutes, the + ``min_alignment_period`` should be at least 10 minutes. It + would not make sense to fetch and align data at one minute + intervals. + """ + class PlotType(proto.Enum): + r"""The types of plotting strategies for data sets.""" + PLOT_TYPE_UNSPECIFIED = 0 + LINE = 1 + STACKED_AREA = 2 + STACKED_BAR = 3 + HEATMAP = 4 + + time_series_query = proto.Field( + proto.MESSAGE, + number=1, + message=metrics.TimeSeriesQuery, + ) + plot_type = proto.Field( + proto.ENUM, + number=2, + enum='XyChart.DataSet.PlotType', + ) + legend_template = proto.Field( + proto.STRING, + number=3, + ) + min_alignment_period = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + + class Axis(proto.Message): + r"""A chart axis. + Attributes: + label (str): + The label of the axis. + scale (google.monitoring.dashboard_v1.types.XyChart.Axis.Scale): + The axis scale. By default, a linear scale is + used. + """ + class Scale(proto.Enum): + r"""Types of scales used in axes.""" + SCALE_UNSPECIFIED = 0 + LINEAR = 1 + LOG10 = 2 + + label = proto.Field( + proto.STRING, + number=1, + ) + scale = proto.Field( + proto.ENUM, + number=2, + enum='XyChart.Axis.Scale', + ) + + data_sets = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=DataSet, + ) + timeshift_duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + thresholds = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=metrics.Threshold, + ) + x_axis = proto.Field( + proto.MESSAGE, + number=6, + message=Axis, + ) + y_axis = proto.Field( + proto.MESSAGE, + number=7, + message=Axis, + ) + chart_options = proto.Field( + proto.MESSAGE, + number=8, + message='ChartOptions', + ) + + +class ChartOptions(proto.Message): + r"""Options to control visual rendering of a chart. + Attributes: + mode (google.monitoring.dashboard_v1.types.ChartOptions.Mode): + The chart mode. + """ + class Mode(proto.Enum): + r"""Chart mode options.""" + MODE_UNSPECIFIED = 0 + COLOR = 1 + X_RAY = 2 + STATS = 3 + + mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..6a8f47f --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/monitoring/dashboard_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py new file mode 100644 index 0000000..db3aefd --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py @@ -0,0 +1,180 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class dashboardCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_dashboard': ('parent', 'dashboard', ), + 'delete_dashboard': ('name', ), + 'get_dashboard': ('name', ), + 'list_dashboards': ('parent', 'page_size', 'page_token', ), + 'update_dashboard': ('dashboard', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=dashboardCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the dashboard client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..85a0d6f --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-monitoring-dashboard', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.monitoring'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py b/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py new file mode 100644 index 0000000..8edb05d --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py @@ -0,0 +1,1924 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.monitoring.dashboard_v1.services.dashboards_service import DashboardsServiceAsyncClient +from google.monitoring.dashboard_v1.services.dashboards_service import DashboardsServiceClient +from google.monitoring.dashboard_v1.services.dashboards_service import pagers +from google.monitoring.dashboard_v1.services.dashboards_service import transports +from google.monitoring.dashboard_v1.services.dashboards_service.transports.base import _GOOGLE_AUTH_VERSION +from google.monitoring.dashboard_v1.types import common +from google.monitoring.dashboard_v1.types import dashboard +from google.monitoring.dashboard_v1.types import dashboards_service +from google.monitoring.dashboard_v1.types import layouts +from google.monitoring.dashboard_v1.types import metrics +from google.monitoring.dashboard_v1.types import scorecard +from google.monitoring.dashboard_v1.types import text +from google.monitoring.dashboard_v1.types import widget +from google.monitoring.dashboard_v1.types import xychart +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DashboardsServiceClient._get_default_mtls_endpoint(None) is None + assert DashboardsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DashboardsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DashboardsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DashboardsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DashboardsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DashboardsServiceClient, + DashboardsServiceAsyncClient, +]) +def test_dashboards_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'monitoring.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + DashboardsServiceClient, + DashboardsServiceAsyncClient, +]) +def test_dashboards_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_called_with(True) + + +@pytest.mark.parametrize("client_class", [ + DashboardsServiceClient, + DashboardsServiceAsyncClient, +]) +def test_dashboards_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'monitoring.googleapis.com:443' + + +def test_dashboards_service_client_get_transport_class(): + transport = DashboardsServiceClient.get_transport_class() + available_transports = [ + transports.DashboardsServiceGrpcTransport, + ] + assert transport in available_transports + + transport = DashboardsServiceClient.get_transport_class("grpc") + assert transport == transports.DashboardsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), + (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DashboardsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceClient)) +@mock.patch.object(DashboardsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceAsyncClient)) +def test_dashboards_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DashboardsServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DashboardsServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc", "true"), + (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc", "false"), + (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DashboardsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceClient)) +@mock.patch.object(DashboardsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dashboards_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), + (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_dashboards_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), + (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_dashboards_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_dashboards_service_client_client_options_from_dict(): + with mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DashboardsServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_dashboard(transport: str = 'grpc', request_type=dashboards_service.CreateDashboardRequest): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dashboard.Dashboard( + name='name_value', + display_name='display_name_value', + etag='etag_value', + grid_layout=layouts.GridLayout(columns=769), + ) + response = client.create_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.CreateDashboardRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +def test_create_dashboard_from_dict(): + test_create_dashboard(request_type=dict) + + +def test_create_dashboard_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dashboard), + '__call__') as call: + client.create_dashboard() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.CreateDashboardRequest() + + +@pytest.mark.asyncio +async def test_create_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.CreateDashboardRequest): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard( + name='name_value', + display_name='display_name_value', + etag='etag_value', + )) + response = await client.create_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.CreateDashboardRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_create_dashboard_async_from_dict(): + await test_create_dashboard_async(request_type=dict) + + +def test_create_dashboard_field_headers(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.CreateDashboardRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dashboard), + '__call__') as call: + call.return_value = dashboard.Dashboard() + client.create_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_dashboard_field_headers_async(): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.CreateDashboardRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_dashboard), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) + await client.create_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_dashboards(transport: str = 'grpc', request_type=dashboards_service.ListDashboardsRequest): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dashboards_service.ListDashboardsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_dashboards(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.ListDashboardsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDashboardsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_dashboards_from_dict(): + test_list_dashboards(request_type=dict) + + +def test_list_dashboards_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__') as call: + client.list_dashboards() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.ListDashboardsRequest() + + +@pytest.mark.asyncio +async def test_list_dashboards_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.ListDashboardsRequest): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboards_service.ListDashboardsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_dashboards(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.ListDashboardsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDashboardsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_dashboards_async_from_dict(): + await test_list_dashboards_async(request_type=dict) + + +def test_list_dashboards_field_headers(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.ListDashboardsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__') as call: + call.return_value = dashboards_service.ListDashboardsResponse() + client.list_dashboards(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_dashboards_field_headers_async(): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.ListDashboardsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboards_service.ListDashboardsResponse()) + await client.list_dashboards(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_dashboards_pager(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + next_page_token='abc', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[], + next_page_token='def', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + ], + next_page_token='ghi', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_dashboards(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, dashboard.Dashboard) + for i in results) + +def test_list_dashboards_pages(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + next_page_token='abc', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[], + next_page_token='def', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + ], + next_page_token='ghi', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + ), + RuntimeError, + ) + pages = list(client.list_dashboards(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_dashboards_async_pager(): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + next_page_token='abc', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[], + next_page_token='def', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + ], + next_page_token='ghi', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_dashboards(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dashboard.Dashboard) + for i in responses) + +@pytest.mark.asyncio +async def test_list_dashboards_async_pages(): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dashboards), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + next_page_token='abc', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[], + next_page_token='def', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + ], + next_page_token='ghi', + ), + dashboards_service.ListDashboardsResponse( + dashboards=[ + dashboard.Dashboard(), + dashboard.Dashboard(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_dashboards(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_dashboard(transport: str = 'grpc', request_type=dashboards_service.GetDashboardRequest): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dashboard.Dashboard( + name='name_value', + display_name='display_name_value', + etag='etag_value', + grid_layout=layouts.GridLayout(columns=769), + ) + response = client.get_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.GetDashboardRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +def test_get_dashboard_from_dict(): + test_get_dashboard(request_type=dict) + + +def test_get_dashboard_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dashboard), + '__call__') as call: + client.get_dashboard() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.GetDashboardRequest() + + +@pytest.mark.asyncio +async def test_get_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.GetDashboardRequest): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard( + name='name_value', + display_name='display_name_value', + etag='etag_value', + )) + response = await client.get_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.GetDashboardRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_dashboard_async_from_dict(): + await test_get_dashboard_async(request_type=dict) + + +def test_get_dashboard_field_headers(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.GetDashboardRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dashboard), + '__call__') as call: + call.return_value = dashboard.Dashboard() + client.get_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_dashboard_field_headers_async(): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.GetDashboardRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_dashboard), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) + await client.get_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_dashboard(transport: str = 'grpc', request_type=dashboards_service.DeleteDashboardRequest): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.DeleteDashboardRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_dashboard_from_dict(): + test_delete_dashboard(request_type=dict) + + +def test_delete_dashboard_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dashboard), + '__call__') as call: + client.delete_dashboard() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.DeleteDashboardRequest() + + +@pytest.mark.asyncio +async def test_delete_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.DeleteDashboardRequest): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.DeleteDashboardRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_dashboard_async_from_dict(): + await test_delete_dashboard_async(request_type=dict) + + +def test_delete_dashboard_field_headers(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.DeleteDashboardRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dashboard), + '__call__') as call: + call.return_value = None + client.delete_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_dashboard_field_headers_async(): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.DeleteDashboardRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_dashboard), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_update_dashboard(transport: str = 'grpc', request_type=dashboards_service.UpdateDashboardRequest): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = dashboard.Dashboard( + name='name_value', + display_name='display_name_value', + etag='etag_value', + grid_layout=layouts.GridLayout(columns=769), + ) + response = client.update_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.UpdateDashboardRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +def test_update_dashboard_from_dict(): + test_update_dashboard(request_type=dict) + + +def test_update_dashboard_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dashboard), + '__call__') as call: + client.update_dashboard() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.UpdateDashboardRequest() + + +@pytest.mark.asyncio +async def test_update_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.UpdateDashboardRequest): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dashboard), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard( + name='name_value', + display_name='display_name_value', + etag='etag_value', + )) + response = await client.update_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == dashboards_service.UpdateDashboardRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_update_dashboard_async_from_dict(): + await test_update_dashboard_async(request_type=dict) + + +def test_update_dashboard_field_headers(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.UpdateDashboardRequest() + + request.dashboard.name = 'dashboard.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dashboard), + '__call__') as call: + call.return_value = dashboard.Dashboard() + client.update_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'dashboard.name=dashboard.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_dashboard_field_headers_async(): + client = DashboardsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dashboards_service.UpdateDashboardRequest() + + request.dashboard.name = 'dashboard.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dashboard), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) + await client.update_dashboard(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'dashboard.name=dashboard.name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DashboardsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DashboardsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DashboardsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DashboardsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DashboardsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DashboardsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DashboardsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DashboardsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DashboardsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DashboardsServiceGrpcTransport, + transports.DashboardsServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DashboardsServiceGrpcTransport, + ) + +def test_dashboards_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DashboardsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_dashboards_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DashboardsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_dashboard', + 'list_dashboards', + 'get_dashboard', + 'delete_dashboard', + 'update_dashboard', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_dashboards_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DashboardsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_dashboards_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DashboardsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ), + quota_project_id="octopus", + ) + + +def test_dashboards_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DashboardsServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_dashboards_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DashboardsServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_dashboards_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DashboardsServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read', 'https://www.googleapis.com/auth/monitoring.write',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DashboardsServiceGrpcTransport, + transports.DashboardsServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_dashboards_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read', 'https://www.googleapis.com/auth/monitoring.write',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DashboardsServiceGrpcTransport, + transports.DashboardsServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_dashboards_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DashboardsServiceGrpcTransport, grpc_helpers), + (transports.DashboardsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_dashboards_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', +), + scopes=["1", "2"], + default_host="monitoring.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport]) +def test_dashboards_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_dashboards_service_host_no_port(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='monitoring.googleapis.com'), + ) + assert client.transport._host == 'monitoring.googleapis.com:443' + + +def test_dashboards_service_host_with_port(): + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='monitoring.googleapis.com:8000'), + ) + assert client.transport._host == 'monitoring.googleapis.com:8000' + +def test_dashboards_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DashboardsServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_dashboards_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DashboardsServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport]) +def test_dashboards_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport]) +def test_dashboards_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_dashboard_path(): + project = "squid" + dashboard = "clam" + expected = "projects/{project}/dashboards/{dashboard}".format(project=project, dashboard=dashboard, ) + actual = DashboardsServiceClient.dashboard_path(project, dashboard) + assert expected == actual + + +def test_parse_dashboard_path(): + expected = { + "project": "whelk", + "dashboard": "octopus", + } + path = DashboardsServiceClient.dashboard_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_dashboard_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DashboardsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = DashboardsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = DashboardsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = DashboardsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DashboardsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = DashboardsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = DashboardsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = DashboardsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DashboardsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = DashboardsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.DashboardsServiceTransport, '_prep_wrapped_messages') as prep: + client = DashboardsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DashboardsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DashboardsServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From 843a9f7b1777c51a029c986dd298e8d5927a1ba9 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 22 Jun 2021 00:10:54 +0000 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md --- .../dashboards_service/transports/base.py | 40 +- .../dashboards_service/transports/grpc.py | 7 +- .../transports/grpc_asyncio.py | 7 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 ---- .../docs/dashboard_v1/dashboards_service.rst | 10 - .../v1/docs/dashboard_v1/services.rst | 6 - .../v1/docs/dashboard_v1/types.rst | 7 - owl-bot-staging/v1/docs/index.rst | 7 - .../google/monitoring/dashboard/__init__.py | 71 - .../v1/google/monitoring/dashboard/py.typed | 2 - .../monitoring/dashboard_v1/__init__.py | 72 - .../dashboard_v1/gapic_metadata.json | 73 - .../google/monitoring/dashboard_v1/py.typed | 2 - .../dashboard_v1/services/__init__.py | 15 - .../services/dashboards_service/__init__.py | 22 - .../dashboards_service/async_client.py | 471 ---- .../services/dashboards_service/client.py | 663 ------ .../services/dashboards_service/pagers.py | 141 -- .../dashboards_service/transports/__init__.py | 33 - .../dashboards_service/transports/base.py | 229 -- .../dashboards_service/transports/grpc.py | 382 ---- .../transports/grpc_asyncio.py | 386 ---- .../monitoring/dashboard_v1/types/__init__.py | 84 - .../monitoring/dashboard_v1/types/common.py | 298 --- .../dashboard_v1/types/dashboard.py | 102 - .../dashboard_v1/types/dashboards_service.py | 175 -- .../dashboard_v1/types/drilldowns.py | 25 - .../monitoring/dashboard_v1/types/layouts.py | 214 -- .../monitoring/dashboard_v1/types/metrics.py | 269 --- .../dashboard_v1/types/scorecard.py | 167 -- .../monitoring/dashboard_v1/types/service.py | 25 - .../monitoring/dashboard_v1/types/text.py | 52 - .../monitoring/dashboard_v1/types/widget.py | 80 - .../monitoring/dashboard_v1/types/xychart.py | 182 -- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 -- .../v1/scripts/fixup_dashboard_v1_keywords.py | 180 -- owl-bot-staging/v1/setup.py | 53 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/dashboard_v1/__init__.py | 16 - .../dashboard_v1/test_dashboards_service.py | 1924 ----------------- .../dashboard_v1/test_dashboards_service.py | 109 +- 47 files changed, 37 insertions(+), 7191 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst delete mode 100644 owl-bot-staging/v1/docs/dashboard_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/dashboard_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard/__init__.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard/py.typed delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py delete mode 100644 owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py index 1363421..938b11c 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.monitoring_dashboard_v1.types import dashboard from google.cloud.monitoring_dashboard_v1.types import dashboards_service @@ -47,8 +48,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class DashboardsServiceTransport(abc.ABC): """Abstract transport class for DashboardsService.""" @@ -71,6 +70,7 @@ def __init__( scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, **kwargs, ) -> None: """Instantiate the transport. @@ -94,6 +94,8 @@ def __init__( API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -122,13 +124,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -149,27 +158,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py index b5186b7..816e86f 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py @@ -152,6 +152,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -207,14 +208,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py index 7c8551d..f04aa16 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py @@ -81,14 +81,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -198,6 +198,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 587e3dd..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/monitoring/dashboard/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 2da1894..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/monitoring/dashboard *.py -recursive-include google/monitoring/dashboard_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 12344c5..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Monitoring Dashboard API -================================================= - -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 billing for your project.`_ -3. Enable the Google Monitoring Dashboard API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -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 - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index c2a0bf9..0000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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. -# -# -# google-monitoring-dashboard 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.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# 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.todo", - "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"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# 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-monitoring-dashboard" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = "alabaster" - -# 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 = { - "description": "Google Monitoring Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# 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 = ["_static"] - -# 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-monitoring-dashboard-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- 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-monitoring-dashboard.tex", - u"google-monitoring-dashboard 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-monitoring-dashboard", - u"Google Monitoring Dashboard 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-monitoring-dashboard", - u"google-monitoring-dashboard Documentation", - author, - "google-monitoring-dashboard", - "GAPIC library for Google Monitoring Dashboard API", - "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), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/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/owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst b/owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst deleted file mode 100644 index 91f68ce..0000000 --- a/owl-bot-staging/v1/docs/dashboard_v1/dashboards_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DashboardsService ------------------------------------ - -.. automodule:: google.monitoring.dashboard_v1.services.dashboards_service - :members: - :inherited-members: - -.. automodule:: google.monitoring.dashboard_v1.services.dashboards_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/dashboard_v1/services.rst b/owl-bot-staging/v1/docs/dashboard_v1/services.rst deleted file mode 100644 index bfcc085..0000000 --- a/owl-bot-staging/v1/docs/dashboard_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Monitoring Dashboard v1 API -=============================================== -.. toctree:: - :maxdepth: 2 - - dashboards_service diff --git a/owl-bot-staging/v1/docs/dashboard_v1/types.rst b/owl-bot-staging/v1/docs/dashboard_v1/types.rst deleted file mode 100644 index 56014d5..0000000 --- a/owl-bot-staging/v1/docs/dashboard_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Monitoring Dashboard v1 API -============================================ - -.. automodule:: google.monitoring.dashboard_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index 41b71cf..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - dashboard_v1/services - dashboard_v1/types diff --git a/owl-bot-staging/v1/google/monitoring/dashboard/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard/__init__.py deleted file mode 100644 index dd8fd5a..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard/__init__.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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.monitoring.dashboard_v1.services.dashboards_service.client import DashboardsServiceClient -from google.monitoring.dashboard_v1.services.dashboards_service.async_client import DashboardsServiceAsyncClient - -from google.monitoring.dashboard_v1.types.common import Aggregation -from google.monitoring.dashboard_v1.types.common import PickTimeSeriesFilter -from google.monitoring.dashboard_v1.types.common import StatisticalTimeSeriesFilter -from google.monitoring.dashboard_v1.types.dashboard import Dashboard -from google.monitoring.dashboard_v1.types.dashboards_service import CreateDashboardRequest -from google.monitoring.dashboard_v1.types.dashboards_service import DeleteDashboardRequest -from google.monitoring.dashboard_v1.types.dashboards_service import GetDashboardRequest -from google.monitoring.dashboard_v1.types.dashboards_service import ListDashboardsRequest -from google.monitoring.dashboard_v1.types.dashboards_service import ListDashboardsResponse -from google.monitoring.dashboard_v1.types.dashboards_service import UpdateDashboardRequest -from google.monitoring.dashboard_v1.types.layouts import ColumnLayout -from google.monitoring.dashboard_v1.types.layouts import GridLayout -from google.monitoring.dashboard_v1.types.layouts import MosaicLayout -from google.monitoring.dashboard_v1.types.layouts import RowLayout -from google.monitoring.dashboard_v1.types.metrics import Threshold -from google.monitoring.dashboard_v1.types.metrics import TimeSeriesFilter -from google.monitoring.dashboard_v1.types.metrics import TimeSeriesFilterRatio -from google.monitoring.dashboard_v1.types.metrics import TimeSeriesQuery -from google.monitoring.dashboard_v1.types.metrics import SparkChartType -from google.monitoring.dashboard_v1.types.scorecard import Scorecard -from google.monitoring.dashboard_v1.types.text import Text -from google.monitoring.dashboard_v1.types.widget import Widget -from google.monitoring.dashboard_v1.types.xychart import ChartOptions -from google.monitoring.dashboard_v1.types.xychart import XyChart - -__all__ = ('DashboardsServiceClient', - 'DashboardsServiceAsyncClient', - 'Aggregation', - 'PickTimeSeriesFilter', - 'StatisticalTimeSeriesFilter', - 'Dashboard', - 'CreateDashboardRequest', - 'DeleteDashboardRequest', - 'GetDashboardRequest', - 'ListDashboardsRequest', - 'ListDashboardsResponse', - 'UpdateDashboardRequest', - 'ColumnLayout', - 'GridLayout', - 'MosaicLayout', - 'RowLayout', - 'Threshold', - 'TimeSeriesFilter', - 'TimeSeriesFilterRatio', - 'TimeSeriesQuery', - 'SparkChartType', - 'Scorecard', - 'Text', - 'Widget', - 'ChartOptions', - 'XyChart', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard/py.typed b/owl-bot-staging/v1/google/monitoring/dashboard/py.typed deleted file mode 100644 index a52708e..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-monitoring-dashboard package uses inline types. diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py deleted file mode 100644 index d297765..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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 .services.dashboards_service import DashboardsServiceClient -from .services.dashboards_service import DashboardsServiceAsyncClient - -from .types.common import Aggregation -from .types.common import PickTimeSeriesFilter -from .types.common import StatisticalTimeSeriesFilter -from .types.dashboard import Dashboard -from .types.dashboards_service import CreateDashboardRequest -from .types.dashboards_service import DeleteDashboardRequest -from .types.dashboards_service import GetDashboardRequest -from .types.dashboards_service import ListDashboardsRequest -from .types.dashboards_service import ListDashboardsResponse -from .types.dashboards_service import UpdateDashboardRequest -from .types.layouts import ColumnLayout -from .types.layouts import GridLayout -from .types.layouts import MosaicLayout -from .types.layouts import RowLayout -from .types.metrics import Threshold -from .types.metrics import TimeSeriesFilter -from .types.metrics import TimeSeriesFilterRatio -from .types.metrics import TimeSeriesQuery -from .types.metrics import SparkChartType -from .types.scorecard import Scorecard -from .types.text import Text -from .types.widget import Widget -from .types.xychart import ChartOptions -from .types.xychart import XyChart - -__all__ = ( - 'DashboardsServiceAsyncClient', -'Aggregation', -'ChartOptions', -'ColumnLayout', -'CreateDashboardRequest', -'Dashboard', -'DashboardsServiceClient', -'DeleteDashboardRequest', -'GetDashboardRequest', -'GridLayout', -'ListDashboardsRequest', -'ListDashboardsResponse', -'MosaicLayout', -'PickTimeSeriesFilter', -'RowLayout', -'Scorecard', -'SparkChartType', -'StatisticalTimeSeriesFilter', -'Text', -'Threshold', -'TimeSeriesFilter', -'TimeSeriesFilterRatio', -'TimeSeriesQuery', -'UpdateDashboardRequest', -'Widget', -'XyChart', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json b/owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json deleted file mode 100644 index 94b72f3..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/gapic_metadata.json +++ /dev/null @@ -1,73 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.monitoring.dashboard_v1", - "protoPackage": "google.monitoring.dashboard.v1", - "schema": "1.0", - "services": { - "DashboardsService": { - "clients": { - "grpc": { - "libraryClient": "DashboardsServiceClient", - "rpcs": { - "CreateDashboard": { - "methods": [ - "create_dashboard" - ] - }, - "DeleteDashboard": { - "methods": [ - "delete_dashboard" - ] - }, - "GetDashboard": { - "methods": [ - "get_dashboard" - ] - }, - "ListDashboards": { - "methods": [ - "list_dashboards" - ] - }, - "UpdateDashboard": { - "methods": [ - "update_dashboard" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DashboardsServiceAsyncClient", - "rpcs": { - "CreateDashboard": { - "methods": [ - "create_dashboard" - ] - }, - "DeleteDashboard": { - "methods": [ - "delete_dashboard" - ] - }, - "GetDashboard": { - "methods": [ - "get_dashboard" - ] - }, - "ListDashboards": { - "methods": [ - "list_dashboards" - ] - }, - "UpdateDashboard": { - "methods": [ - "update_dashboard" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed b/owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed deleted file mode 100644 index a52708e..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-monitoring-dashboard package uses inline types. diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py deleted file mode 100644 index 879347b..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import DashboardsServiceClient -from .async_client import DashboardsServiceAsyncClient - -__all__ = ( - 'DashboardsServiceClient', - 'DashboardsServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py deleted file mode 100644 index e1a5eca..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/async_client.py +++ /dev/null @@ -1,471 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.monitoring.dashboard_v1.services.dashboards_service import pagers -from google.monitoring.dashboard_v1.types import dashboard -from google.monitoring.dashboard_v1.types import dashboards_service -from google.monitoring.dashboard_v1.types import layouts -from .transports.base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport -from .client import DashboardsServiceClient - - -class DashboardsServiceAsyncClient: - """Manages Stackdriver dashboards. A dashboard is an arrangement - of data display widgets in a specific layout. - """ - - _client: DashboardsServiceClient - - DEFAULT_ENDPOINT = DashboardsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DashboardsServiceClient.DEFAULT_MTLS_ENDPOINT - - dashboard_path = staticmethod(DashboardsServiceClient.dashboard_path) - parse_dashboard_path = staticmethod(DashboardsServiceClient.parse_dashboard_path) - common_billing_account_path = staticmethod(DashboardsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DashboardsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DashboardsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DashboardsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DashboardsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DashboardsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DashboardsServiceClient.common_project_path) - parse_common_project_path = staticmethod(DashboardsServiceClient.parse_common_project_path) - common_location_path = staticmethod(DashboardsServiceClient.common_location_path) - parse_common_location_path = staticmethod(DashboardsServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DashboardsServiceAsyncClient: The constructed client. - """ - return DashboardsServiceClient.from_service_account_info.__func__(DashboardsServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DashboardsServiceAsyncClient: The constructed client. - """ - return DashboardsServiceClient.from_service_account_file.__func__(DashboardsServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DashboardsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DashboardsServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DashboardsServiceClient).get_transport_class, type(DashboardsServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, DashboardsServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the dashboards service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.DashboardsServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DashboardsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_dashboard(self, - request: dashboards_service.CreateDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Creates a new custom dashboard. For examples on how you can use - this API to create dashboards, see `Managing dashboards by - API `__. - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information about - permissions, see `Cloud Identity and Access - Management `__. - - Args: - request (:class:`google.monitoring.dashboard_v1.types.CreateDashboardRequest`): - The request object. The `CreateDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.types.Dashboard: - A Google Stackdriver dashboard. - Dashboards define the content and layout - of pages in the Stackdriver web - application. - - """ - # Create or coerce a protobuf request object. - request = dashboards_service.CreateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_dashboard, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_dashboards(self, - request: dashboards_service.ListDashboardsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDashboardsAsyncPager: - r"""Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (:class:`google.monitoring.dashboard_v1.types.ListDashboardsRequest`): - The request object. The `ListDashboards` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.services.dashboards_service.pagers.ListDashboardsAsyncPager: - The ListDashboards request. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = dashboards_service.ListDashboardsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_dashboards, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDashboardsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_dashboard(self, - request: dashboards_service.GetDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (:class:`google.monitoring.dashboard_v1.types.GetDashboardRequest`): - The request object. The `GetDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.types.Dashboard: - A Google Stackdriver dashboard. - Dashboards define the content and layout - of pages in the Stackdriver web - application. - - """ - # Create or coerce a protobuf request object. - request = dashboards_service.GetDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_dashboard, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_dashboard(self, - request: dashboards_service.DeleteDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (:class:`google.monitoring.dashboard_v1.types.DeleteDashboardRequest`): - The request object. The `DeleteDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - request = dashboards_service.DeleteDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_dashboard, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_dashboard(self, - request: dashboards_service.UpdateDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (:class:`google.monitoring.dashboard_v1.types.UpdateDashboardRequest`): - The request object. The `UpdateDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.types.Dashboard: - A Google Stackdriver dashboard. - Dashboards define the content and layout - of pages in the Stackdriver web - application. - - """ - # Create or coerce a protobuf request object. - request = dashboards_service.UpdateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_dashboard, - default_timeout=30.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dashboard.name", request.dashboard.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-monitoring-dashboard", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DashboardsServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py deleted file mode 100644 index 1aa9896..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/client.py +++ /dev/null @@ -1,663 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.monitoring.dashboard_v1.services.dashboards_service import pagers -from google.monitoring.dashboard_v1.types import dashboard -from google.monitoring.dashboard_v1.types import dashboards_service -from google.monitoring.dashboard_v1.types import layouts -from .transports.base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DashboardsServiceGrpcTransport -from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport - - -class DashboardsServiceClientMeta(type): - """Metaclass for the DashboardsService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DashboardsServiceTransport]] - _transport_registry["grpc"] = DashboardsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DashboardsServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[DashboardsServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DashboardsServiceClient(metaclass=DashboardsServiceClientMeta): - """Manages Stackdriver dashboards. A dashboard is an arrangement - of data display widgets in a specific layout. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "monitoring.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DashboardsServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DashboardsServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DashboardsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DashboardsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def dashboard_path(project: str,dashboard: str,) -> str: - """Returns a fully-qualified dashboard string.""" - return "projects/{project}/dashboards/{dashboard}".format(project=project, dashboard=dashboard, ) - - @staticmethod - def parse_dashboard_path(path: str) -> Dict[str,str]: - """Parses a dashboard path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/dashboards/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DashboardsServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the dashboards service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DashboardsServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DashboardsServiceTransport): - # transport is a DashboardsServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def create_dashboard(self, - request: dashboards_service.CreateDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Creates a new custom dashboard. For examples on how you can use - this API to create dashboards, see `Managing dashboards by - API `__. - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information about - permissions, see `Cloud Identity and Access - Management `__. - - Args: - request (google.monitoring.dashboard_v1.types.CreateDashboardRequest): - The request object. The `CreateDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.types.Dashboard: - A Google Stackdriver dashboard. - Dashboards define the content and layout - of pages in the Stackdriver web - application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a dashboards_service.CreateDashboardRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, dashboards_service.CreateDashboardRequest): - request = dashboards_service.CreateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_dashboards(self, - request: dashboards_service.ListDashboardsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDashboardsPager: - r"""Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (google.monitoring.dashboard_v1.types.ListDashboardsRequest): - The request object. The `ListDashboards` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.services.dashboards_service.pagers.ListDashboardsPager: - The ListDashboards request. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a dashboards_service.ListDashboardsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, dashboards_service.ListDashboardsRequest): - request = dashboards_service.ListDashboardsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_dashboards] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDashboardsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_dashboard(self, - request: dashboards_service.GetDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (google.monitoring.dashboard_v1.types.GetDashboardRequest): - The request object. The `GetDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.types.Dashboard: - A Google Stackdriver dashboard. - Dashboards define the content and layout - of pages in the Stackdriver web - application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a dashboards_service.GetDashboardRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, dashboards_service.GetDashboardRequest): - request = dashboards_service.GetDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_dashboard(self, - request: dashboards_service.DeleteDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (google.monitoring.dashboard_v1.types.DeleteDashboardRequest): - The request object. The `DeleteDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a dashboards_service.DeleteDashboardRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, dashboards_service.DeleteDashboardRequest): - request = dashboards_service.DeleteDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_dashboard(self, - request: dashboards_service.UpdateDashboardRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> dashboard.Dashboard: - r"""Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Args: - request (google.monitoring.dashboard_v1.types.UpdateDashboardRequest): - The request object. The `UpdateDashboard` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.monitoring.dashboard_v1.types.Dashboard: - A Google Stackdriver dashboard. - Dashboards define the content and layout - of pages in the Stackdriver web - application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a dashboards_service.UpdateDashboardRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, dashboards_service.UpdateDashboardRequest): - request = dashboards_service.UpdateDashboardRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_dashboard] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("dashboard.name", request.dashboard.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-monitoring-dashboard", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DashboardsServiceClient", -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py deleted file mode 100644 index 2ec062b..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.monitoring.dashboard_v1.types import dashboard -from google.monitoring.dashboard_v1.types import dashboards_service - - -class ListDashboardsPager: - """A pager for iterating through ``list_dashboards`` requests. - - This class thinly wraps an initial - :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``dashboards`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDashboards`` requests and continue to iterate - through the ``dashboards`` field on the - corresponding responses. - - All the usual :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., dashboards_service.ListDashboardsResponse], - request: dashboards_service.ListDashboardsRequest, - response: dashboards_service.ListDashboardsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.monitoring.dashboard_v1.types.ListDashboardsRequest): - The initial request object. - response (google.monitoring.dashboard_v1.types.ListDashboardsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dashboards_service.ListDashboardsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[dashboards_service.ListDashboardsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[dashboard.Dashboard]: - for page in self.pages: - yield from page.dashboards - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDashboardsAsyncPager: - """A pager for iterating through ``list_dashboards`` requests. - - This class thinly wraps an initial - :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``dashboards`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDashboards`` requests and continue to iterate - through the ``dashboards`` field on the - corresponding responses. - - All the usual :class:`google.monitoring.dashboard_v1.types.ListDashboardsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[dashboards_service.ListDashboardsResponse]], - request: dashboards_service.ListDashboardsRequest, - response: dashboards_service.ListDashboardsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.monitoring.dashboard_v1.types.ListDashboardsRequest): - The initial request object. - response (google.monitoring.dashboard_v1.types.ListDashboardsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = dashboards_service.ListDashboardsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[dashboards_service.ListDashboardsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[dashboard.Dashboard]: - async def async_generator(): - async for page in self.pages: - for response in page.dashboards: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py deleted file mode 100644 index 2d413c9..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DashboardsServiceTransport -from .grpc import DashboardsServiceGrpcTransport -from .grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DashboardsServiceTransport]] -_transport_registry['grpc'] = DashboardsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DashboardsServiceGrpcAsyncIOTransport - -__all__ = ( - 'DashboardsServiceTransport', - 'DashboardsServiceGrpcTransport', - 'DashboardsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py deleted file mode 100644 index 194aaae..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/base.py +++ /dev/null @@ -1,229 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.monitoring.dashboard_v1.types import dashboard -from google.monitoring.dashboard_v1.types import dashboards_service -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-monitoring-dashboard', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class DashboardsServiceTransport(abc.ABC): - """Abstract transport class for DashboardsService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ) - - DEFAULT_HOST: str = 'monitoring.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_dashboard: gapic_v1.method.wrap_method( - self.create_dashboard, - default_timeout=30.0, - client_info=client_info, - ), - self.list_dashboards: gapic_v1.method.wrap_method( - self.list_dashboards, - default_timeout=None, - client_info=client_info, - ), - self.get_dashboard: gapic_v1.method.wrap_method( - self.get_dashboard, - default_timeout=None, - client_info=client_info, - ), - self.delete_dashboard: gapic_v1.method.wrap_method( - self.delete_dashboard, - default_timeout=30.0, - client_info=client_info, - ), - self.update_dashboard: gapic_v1.method.wrap_method( - self.update_dashboard, - default_timeout=30.0, - client_info=client_info, - ), - } - - @property - def create_dashboard(self) -> Callable[ - [dashboards_service.CreateDashboardRequest], - Union[ - dashboard.Dashboard, - Awaitable[dashboard.Dashboard] - ]]: - raise NotImplementedError() - - @property - def list_dashboards(self) -> Callable[ - [dashboards_service.ListDashboardsRequest], - Union[ - dashboards_service.ListDashboardsResponse, - Awaitable[dashboards_service.ListDashboardsResponse] - ]]: - raise NotImplementedError() - - @property - def get_dashboard(self) -> Callable[ - [dashboards_service.GetDashboardRequest], - Union[ - dashboard.Dashboard, - Awaitable[dashboard.Dashboard] - ]]: - raise NotImplementedError() - - @property - def delete_dashboard(self) -> Callable[ - [dashboards_service.DeleteDashboardRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_dashboard(self) -> Callable[ - [dashboards_service.UpdateDashboardRequest], - Union[ - dashboard.Dashboard, - Awaitable[dashboard.Dashboard] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'DashboardsServiceTransport', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py deleted file mode 100644 index cb50a85..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc.py +++ /dev/null @@ -1,382 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.monitoring.dashboard_v1.types import dashboard -from google.monitoring.dashboard_v1.types import dashboards_service -from google.protobuf import empty_pb2 # type: ignore -from .base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO - - -class DashboardsServiceGrpcTransport(DashboardsServiceTransport): - """gRPC backend transport for DashboardsService. - - Manages Stackdriver dashboards. A dashboard is an arrangement - of data display widgets in a specific layout. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'monitoring.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'monitoring.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_dashboard(self) -> Callable[ - [dashboards_service.CreateDashboardRequest], - dashboard.Dashboard]: - r"""Return a callable for the create dashboard method over gRPC. - - Creates a new custom dashboard. For examples on how you can use - this API to create dashboards, see `Managing dashboards by - API `__. - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information about - permissions, see `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.CreateDashboardRequest], - ~.Dashboard]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_dashboard' not in self._stubs: - self._stubs['create_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard', - request_serializer=dashboards_service.CreateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs['create_dashboard'] - - @property - def list_dashboards(self) -> Callable[ - [dashboards_service.ListDashboardsRequest], - dashboards_service.ListDashboardsResponse]: - r"""Return a callable for the list dashboards method over gRPC. - - Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.ListDashboardsRequest], - ~.ListDashboardsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_dashboards' not in self._stubs: - self._stubs['list_dashboards'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/ListDashboards', - request_serializer=dashboards_service.ListDashboardsRequest.serialize, - response_deserializer=dashboards_service.ListDashboardsResponse.deserialize, - ) - return self._stubs['list_dashboards'] - - @property - def get_dashboard(self) -> Callable[ - [dashboards_service.GetDashboardRequest], - dashboard.Dashboard]: - r"""Return a callable for the get dashboard method over gRPC. - - Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.GetDashboardRequest], - ~.Dashboard]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_dashboard' not in self._stubs: - self._stubs['get_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/GetDashboard', - request_serializer=dashboards_service.GetDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs['get_dashboard'] - - @property - def delete_dashboard(self) -> Callable[ - [dashboards_service.DeleteDashboardRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete dashboard method over gRPC. - - Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.DeleteDashboardRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_dashboard' not in self._stubs: - self._stubs['delete_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard', - request_serializer=dashboards_service.DeleteDashboardRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_dashboard'] - - @property - def update_dashboard(self) -> Callable[ - [dashboards_service.UpdateDashboardRequest], - dashboard.Dashboard]: - r"""Return a callable for the update dashboard method over gRPC. - - Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.UpdateDashboardRequest], - ~.Dashboard]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_dashboard' not in self._stubs: - self._stubs['update_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard', - request_serializer=dashboards_service.UpdateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs['update_dashboard'] - - -__all__ = ( - 'DashboardsServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py deleted file mode 100644 index fadb181..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,386 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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 warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.monitoring.dashboard_v1.types import dashboard -from google.monitoring.dashboard_v1.types import dashboards_service -from google.protobuf import empty_pb2 # type: ignore -from .base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DashboardsServiceGrpcTransport - - -class DashboardsServiceGrpcAsyncIOTransport(DashboardsServiceTransport): - """gRPC AsyncIO backend transport for DashboardsService. - - Manages Stackdriver dashboards. A dashboard is an arrangement - of data display widgets in a specific layout. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'monitoring.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'monitoring.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_dashboard(self) -> Callable[ - [dashboards_service.CreateDashboardRequest], - Awaitable[dashboard.Dashboard]]: - r"""Return a callable for the create dashboard method over gRPC. - - Creates a new custom dashboard. For examples on how you can use - this API to create dashboards, see `Managing dashboards by - API `__. - This method requires the ``monitoring.dashboards.create`` - permission on the specified project. For more information about - permissions, see `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.CreateDashboardRequest], - Awaitable[~.Dashboard]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_dashboard' not in self._stubs: - self._stubs['create_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard', - request_serializer=dashboards_service.CreateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs['create_dashboard'] - - @property - def list_dashboards(self) -> Callable[ - [dashboards_service.ListDashboardsRequest], - Awaitable[dashboards_service.ListDashboardsResponse]]: - r"""Return a callable for the list dashboards method over gRPC. - - Lists the existing dashboards. - - This method requires the ``monitoring.dashboards.list`` - permission on the specified project. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.ListDashboardsRequest], - Awaitable[~.ListDashboardsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_dashboards' not in self._stubs: - self._stubs['list_dashboards'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/ListDashboards', - request_serializer=dashboards_service.ListDashboardsRequest.serialize, - response_deserializer=dashboards_service.ListDashboardsResponse.deserialize, - ) - return self._stubs['list_dashboards'] - - @property - def get_dashboard(self) -> Callable[ - [dashboards_service.GetDashboardRequest], - Awaitable[dashboard.Dashboard]]: - r"""Return a callable for the get dashboard method over gRPC. - - Fetches a specific dashboard. - - This method requires the ``monitoring.dashboards.get`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.GetDashboardRequest], - Awaitable[~.Dashboard]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_dashboard' not in self._stubs: - self._stubs['get_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/GetDashboard', - request_serializer=dashboards_service.GetDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs['get_dashboard'] - - @property - def delete_dashboard(self) -> Callable[ - [dashboards_service.DeleteDashboardRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete dashboard method over gRPC. - - Deletes an existing custom dashboard. - - This method requires the ``monitoring.dashboards.delete`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.DeleteDashboardRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_dashboard' not in self._stubs: - self._stubs['delete_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard', - request_serializer=dashboards_service.DeleteDashboardRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_dashboard'] - - @property - def update_dashboard(self) -> Callable[ - [dashboards_service.UpdateDashboardRequest], - Awaitable[dashboard.Dashboard]]: - r"""Return a callable for the update dashboard method over gRPC. - - Replaces an existing custom dashboard with a new definition. - - This method requires the ``monitoring.dashboards.update`` - permission on the specified dashboard. For more information, see - `Cloud Identity and Access - Management `__. - - Returns: - Callable[[~.UpdateDashboardRequest], - Awaitable[~.Dashboard]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_dashboard' not in self._stubs: - self._stubs['update_dashboard'] = self.grpc_channel.unary_unary( - '/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard', - request_serializer=dashboards_service.UpdateDashboardRequest.serialize, - response_deserializer=dashboard.Dashboard.deserialize, - ) - return self._stubs['update_dashboard'] - - -__all__ = ( - 'DashboardsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py deleted file mode 100644 index eca1b1c..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/__init__.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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 .common import ( - Aggregation, - PickTimeSeriesFilter, - StatisticalTimeSeriesFilter, -) -from .dashboard import ( - Dashboard, -) -from .dashboards_service import ( - CreateDashboardRequest, - DeleteDashboardRequest, - GetDashboardRequest, - ListDashboardsRequest, - ListDashboardsResponse, - UpdateDashboardRequest, -) -from .layouts import ( - ColumnLayout, - GridLayout, - MosaicLayout, - RowLayout, -) -from .metrics import ( - Threshold, - TimeSeriesFilter, - TimeSeriesFilterRatio, - TimeSeriesQuery, - SparkChartType, -) -from .scorecard import ( - Scorecard, -) -from .text import ( - Text, -) -from .widget import ( - Widget, -) -from .xychart import ( - ChartOptions, - XyChart, -) - -__all__ = ( - 'Aggregation', - 'PickTimeSeriesFilter', - 'StatisticalTimeSeriesFilter', - 'Dashboard', - 'CreateDashboardRequest', - 'DeleteDashboardRequest', - 'GetDashboardRequest', - 'ListDashboardsRequest', - 'ListDashboardsResponse', - 'UpdateDashboardRequest', - 'ColumnLayout', - 'GridLayout', - 'MosaicLayout', - 'RowLayout', - 'Threshold', - 'TimeSeriesFilter', - 'TimeSeriesFilterRatio', - 'TimeSeriesQuery', - 'SparkChartType', - 'Scorecard', - 'Text', - 'Widget', - 'ChartOptions', - 'XyChart', -) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py deleted file mode 100644 index f686374..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/common.py +++ /dev/null @@ -1,298 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'Aggregation', - 'PickTimeSeriesFilter', - 'StatisticalTimeSeriesFilter', - }, -) - - -class Aggregation(proto.Message): - r"""Describes how to combine multiple time series to provide a different - view of the data. Aggregation of time series is done in two steps. - First, each time series in the set is *aligned* to the same time - interval boundaries, then the set of time series is optionally - *reduced* in number. - - Alignment consists of applying the ``per_series_aligner`` operation - to each time series after its data has been divided into regular - ``alignment_period`` time intervals. This process takes *all* of the - data points in an alignment period, applies a mathematical - transformation such as averaging, minimum, maximum, delta, etc., and - converts them into a single data point per period. - - Reduction is when the aligned and transformed time series can - optionally be combined, reducing the number of time series through - similar mathematical transformations. Reduction involves applying a - ``cross_series_reducer`` to all the time series, optionally sorting - the time series into subsets with ``group_by_fields``, and applying - the reducer to each subset. - - The raw time series data can contain a huge amount of information - from multiple sources. Alignment and reduction transforms this mass - of data into a more manageable and representative collection of - data, for example "the 95% latency across the average of all tasks - in a cluster". This representative data can be more easily graphed - and comprehended, and the individual time series data is still - available for later drilldown. For more details, see `Filtering and - aggregation `__. - - Attributes: - alignment_period (google.protobuf.duration_pb2.Duration): - The ``alignment_period`` specifies a time interval, in - seconds, that is used to divide the data in all the [time - series][google.monitoring.v3.TimeSeries] into consistent - blocks of time. This will be done before the per-series - aligner can be applied to the data. - - The value must be at least 60 seconds. If a per-series - aligner other than ``ALIGN_NONE`` is specified, this field - is required or an error is returned. If no per-series - aligner is specified, or the aligner ``ALIGN_NONE`` is - specified, then this field is ignored. - - The maximum value of the ``alignment_period`` is 2 years, or - 104 weeks. - per_series_aligner (google.monitoring.dashboard_v1.types.Aggregation.Aligner): - An ``Aligner`` describes how to bring the data points in a - single time series into temporal alignment. Except for - ``ALIGN_NONE``, all alignments cause all the data points in - an ``alignment_period`` to be mathematically grouped - together, resulting in a single data point for each - ``alignment_period`` with end timestamp at the end of the - period. - - Not all alignment operations may be applied to all time - series. The valid choices depend on the ``metric_kind`` and - ``value_type`` of the original time series. Alignment can - change the ``metric_kind`` or the ``value_type`` of the time - series. - - Time series data must be aligned in order to perform - cross-time series reduction. If ``cross_series_reducer`` is - specified, then ``per_series_aligner`` must be specified and - not equal to ``ALIGN_NONE`` and ``alignment_period`` must be - specified; otherwise, an error is returned. - cross_series_reducer (google.monitoring.dashboard_v1.types.Aggregation.Reducer): - The reduction operation to be used to combine time series - into a single time series, where the value of each data - point in the resulting series is a function of all the - already aligned values in the input time series. - - Not all reducer operations can be applied to all time - series. The valid choices depend on the ``metric_kind`` and - the ``value_type`` of the original time series. Reduction - can yield a time series with a different ``metric_kind`` or - ``value_type`` than the input time series. - - Time series data must first be aligned (see - ``per_series_aligner``) in order to perform cross-time - series reduction. If ``cross_series_reducer`` is specified, - then ``per_series_aligner`` must be specified, and must not - be ``ALIGN_NONE``. An ``alignment_period`` must also be - specified; otherwise, an error is returned. - group_by_fields (Sequence[str]): - The set of fields to preserve when ``cross_series_reducer`` - is specified. The ``group_by_fields`` determine how the time - series are partitioned into subsets prior to applying the - aggregation operation. Each subset contains time series that - have the same value for each of the grouping fields. Each - individual time series is a member of exactly one subset. - The ``cross_series_reducer`` is applied to each subset of - time series. It is not possible to reduce across different - resource types, so this field implicitly contains - ``resource.type``. Fields not specified in - ``group_by_fields`` are aggregated away. If - ``group_by_fields`` is not specified and all the time series - have the same resource type, then the time series are - aggregated into a single output time series. If - ``cross_series_reducer`` is not defined, this field is - ignored. - """ - class Aligner(proto.Enum): - r"""The ``Aligner`` specifies the operation that will be applied to the - data points in each alignment period in a time series. Except for - ``ALIGN_NONE``, which specifies that no operation be applied, each - alignment operation replaces the set of data values in each - alignment period with a single value: the result of applying the - operation to the data values. An aligned time series has a single - data value at the end of each ``alignment_period``. - - An alignment operation can change the data type of the values, too. - For example, if you apply a counting operation to boolean values, - the data ``value_type`` in the original time series is ``BOOLEAN``, - but the ``value_type`` in the aligned result is ``INT64``. - """ - ALIGN_NONE = 0 - ALIGN_DELTA = 1 - ALIGN_RATE = 2 - ALIGN_INTERPOLATE = 3 - ALIGN_NEXT_OLDER = 4 - ALIGN_MIN = 10 - ALIGN_MAX = 11 - ALIGN_MEAN = 12 - ALIGN_COUNT = 13 - ALIGN_SUM = 14 - ALIGN_STDDEV = 15 - ALIGN_COUNT_TRUE = 16 - ALIGN_COUNT_FALSE = 24 - ALIGN_FRACTION_TRUE = 17 - ALIGN_PERCENTILE_99 = 18 - ALIGN_PERCENTILE_95 = 19 - ALIGN_PERCENTILE_50 = 20 - ALIGN_PERCENTILE_05 = 21 - ALIGN_PERCENT_CHANGE = 23 - - class Reducer(proto.Enum): - r"""A Reducer operation describes how to aggregate data points - from multiple time series into a single time series, where the - value of each data point in the resulting series is a function - of all the already aligned values in the input time series. - """ - REDUCE_NONE = 0 - REDUCE_MEAN = 1 - REDUCE_MIN = 2 - REDUCE_MAX = 3 - REDUCE_SUM = 4 - REDUCE_STDDEV = 5 - REDUCE_COUNT = 6 - REDUCE_COUNT_TRUE = 7 - REDUCE_COUNT_FALSE = 15 - REDUCE_FRACTION_TRUE = 8 - REDUCE_PERCENTILE_99 = 9 - REDUCE_PERCENTILE_95 = 10 - REDUCE_PERCENTILE_50 = 11 - REDUCE_PERCENTILE_05 = 12 - - alignment_period = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - per_series_aligner = proto.Field( - proto.ENUM, - number=2, - enum=Aligner, - ) - cross_series_reducer = proto.Field( - proto.ENUM, - number=4, - enum=Reducer, - ) - group_by_fields = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class PickTimeSeriesFilter(proto.Message): - r"""Describes a ranking-based time series filter. Each input time series - is ranked with an aligner. The filter will allow up to - ``num_time_series`` time series to pass through it, selecting them - based on the relative ranking. - - For example, if ``ranking_method`` is - ``METHOD_MEAN``,\ ``direction`` is ``BOTTOM``, and - ``num_time_series`` is 3, then the 3 times series with the lowest - mean values will pass through the filter. - - Attributes: - ranking_method (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter.Method): - ``ranking_method`` is applied to each time series - independently to produce the value which will be used to - compare the time series to other time series. - num_time_series (int): - How many time series to allow to pass through - the filter. - direction (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter.Direction): - How to use the ranking to select time series - that pass through the filter. - """ - class Method(proto.Enum): - r"""The value reducers that can be applied to a - ``PickTimeSeriesFilter``. - """ - METHOD_UNSPECIFIED = 0 - METHOD_MEAN = 1 - METHOD_MAX = 2 - METHOD_MIN = 3 - METHOD_SUM = 4 - METHOD_LATEST = 5 - - class Direction(proto.Enum): - r"""Describes the ranking directions.""" - DIRECTION_UNSPECIFIED = 0 - TOP = 1 - BOTTOM = 2 - - ranking_method = proto.Field( - proto.ENUM, - number=1, - enum=Method, - ) - num_time_series = proto.Field( - proto.INT32, - number=2, - ) - direction = proto.Field( - proto.ENUM, - number=3, - enum=Direction, - ) - - -class StatisticalTimeSeriesFilter(proto.Message): - r"""A filter that ranks streams based on their statistical - relation to other streams in a request. - Note: This field is deprecated and completely ignored by the - API. - - Attributes: - ranking_method (google.monitoring.dashboard_v1.types.StatisticalTimeSeriesFilter.Method): - ``rankingMethod`` is applied to a set of time series, and - then the produced value for each individual time series is - used to compare a given time series to others. These are - methods that cannot be applied stream-by-stream, but rather - require the full context of a request to evaluate time - series. - num_time_series (int): - How many time series to output. - """ - class Method(proto.Enum): - r"""The filter methods that can be applied to a stream.""" - METHOD_UNSPECIFIED = 0 - METHOD_CLUSTER_OUTLIER = 1 - - ranking_method = proto.Field( - proto.ENUM, - number=1, - enum=Method, - ) - num_time_series = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py deleted file mode 100644 index 5ec2395..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboard.py +++ /dev/null @@ -1,102 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import layouts - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'Dashboard', - }, -) - - -class Dashboard(proto.Message): - r"""A Google Stackdriver dashboard. Dashboards define the content - and layout of pages in the Stackdriver web application. - - Attributes: - name (str): - Immutable. The resource name of the - dashboard. - display_name (str): - Required. The mutable, human-readable name. - etag (str): - ``etag`` is used for optimistic concurrency control as a way - to help prevent simultaneous updates of a policy from - overwriting each other. An ``etag`` is returned in the - response to ``GetDashboard``, and users are expected to put - that etag in the request to ``UpdateDashboard`` to ensure - that their change will be applied to the same version of the - Dashboard configuration. The field should not be passed - during dashboard creation. - grid_layout (google.monitoring.dashboard_v1.types.GridLayout): - Content is arranged with a basic layout that - re-flows a simple list of informational elements - like widgets or tiles. - mosaic_layout (google.monitoring.dashboard_v1.types.MosaicLayout): - The content is arranged as a grid of tiles, - with each content widget occupying one or more - grid blocks. - row_layout (google.monitoring.dashboard_v1.types.RowLayout): - The content is divided into equally spaced - rows and the widgets are arranged horizontally. - column_layout (google.monitoring.dashboard_v1.types.ColumnLayout): - The content is divided into equally spaced - columns and the widgets are arranged vertically. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - etag = proto.Field( - proto.STRING, - number=4, - ) - grid_layout = proto.Field( - proto.MESSAGE, - number=5, - oneof='layout', - message=layouts.GridLayout, - ) - mosaic_layout = proto.Field( - proto.MESSAGE, - number=6, - oneof='layout', - message=layouts.MosaicLayout, - ) - row_layout = proto.Field( - proto.MESSAGE, - number=8, - oneof='layout', - message=layouts.RowLayout, - ) - column_layout = proto.Field( - proto.MESSAGE, - number=9, - oneof='layout', - message=layouts.ColumnLayout, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py deleted file mode 100644 index 4cf415e..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/dashboards_service.py +++ /dev/null @@ -1,175 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import dashboard as gmd_dashboard - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'CreateDashboardRequest', - 'ListDashboardsRequest', - 'ListDashboardsResponse', - 'GetDashboardRequest', - 'DeleteDashboardRequest', - 'UpdateDashboardRequest', - }, -) - - -class CreateDashboardRequest(proto.Message): - r"""The ``CreateDashboard`` request. - Attributes: - parent (str): - Required. The project on which to execute the request. The - format is: - - :: - - projects/[PROJECT_ID_OR_NUMBER] - - The ``[PROJECT_ID_OR_NUMBER]`` must match the dashboard - resource name. - dashboard (google.monitoring.dashboard_v1.types.Dashboard): - Required. The initial dashboard - specification. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - dashboard = proto.Field( - proto.MESSAGE, - number=2, - message=gmd_dashboard.Dashboard, - ) - - -class ListDashboardsRequest(proto.Message): - r"""The ``ListDashboards`` request. - Attributes: - parent (str): - Required. The scope of the dashboards to list. The format - is: - - :: - - projects/[PROJECT_ID_OR_NUMBER] - page_size (int): - A positive number that is the maximum number - of results to return. If unspecified, a default - of 1000 is used. - page_token (str): - If this field is not empty then it must contain the - ``nextPageToken`` value returned by a previous call to this - method. Using this field causes the method to return - additional results from the previous method call. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListDashboardsResponse(proto.Message): - r"""The ``ListDashboards`` request. - Attributes: - dashboards (Sequence[google.monitoring.dashboard_v1.types.Dashboard]): - The list of requested dashboards. - next_page_token (str): - If there are more results than have been returned, then this - field is set to a non-empty value. To see the additional - results, use that value as ``page_token`` in the next call - to this method. - """ - - @property - def raw_page(self): - return self - - dashboards = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmd_dashboard.Dashboard, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetDashboardRequest(proto.Message): - r"""The ``GetDashboard`` request. - Attributes: - name (str): - Required. The resource name of the Dashboard. The format is - one of: - - - ``dashboards/[DASHBOARD_ID]`` (for system dashboards) - - ``projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID]`` - (for custom dashboards). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteDashboardRequest(proto.Message): - r"""The ``DeleteDashboard`` request. - Attributes: - name (str): - Required. The resource name of the Dashboard. The format is: - - :: - - projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID] - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateDashboardRequest(proto.Message): - r"""The ``UpdateDashboard`` request. - Attributes: - dashboard (google.monitoring.dashboard_v1.types.Dashboard): - Required. The dashboard that will replace the - existing dashboard. - """ - - dashboard = proto.Field( - proto.MESSAGE, - number=1, - message=gmd_dashboard.Dashboard, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py deleted file mode 100644 index 041e5fd..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/drilldowns.py +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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. -# - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py deleted file mode 100644 index 1ea90ce..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/layouts.py +++ /dev/null @@ -1,214 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import widget as gmd_widget - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'GridLayout', - 'MosaicLayout', - 'RowLayout', - 'ColumnLayout', - }, -) - - -class GridLayout(proto.Message): - r"""A basic layout divides the available space into vertical - columns of equal width and arranges a list of widgets using a - row-first strategy. - - Attributes: - columns (int): - The number of columns into which the view's - width is divided. If omitted or set to zero, a - system default will be used while rendering. - widgets (Sequence[google.monitoring.dashboard_v1.types.Widget]): - The informational elements that are arranged - into the columns row-first. - """ - - columns = proto.Field( - proto.INT64, - number=1, - ) - widgets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gmd_widget.Widget, - ) - - -class MosaicLayout(proto.Message): - r"""A mosaic layout divides the available space into a grid of blocks, - and overlays the grid with tiles. Unlike ``GridLayout``, tiles may - span multiple grid blocks and can be placed at arbitrary locations - in the grid. - - Attributes: - columns (int): - The number of columns in the mosaic grid. The - number of columns must be between 1 and 12, - inclusive. - tiles (Sequence[google.monitoring.dashboard_v1.types.MosaicLayout.Tile]): - The tiles to display. - """ - - class Tile(proto.Message): - r"""A single tile in the mosaic. The placement and size of the - tile are configurable. - - Attributes: - x_pos (int): - The zero-indexed position of the tile in grid blocks - relative to the left edge of the grid. Tiles must be - contained within the specified number of columns. ``x_pos`` - cannot be negative. - y_pos (int): - The zero-indexed position of the tile in grid blocks - relative to the top edge of the grid. ``y_pos`` cannot be - negative. - width (int): - The width of the tile, measured in grid - blocks. Tiles must have a minimum width of 1. - height (int): - The height of the tile, measured in grid - blocks. Tiles must have a minimum height of 1. - widget (google.monitoring.dashboard_v1.types.Widget): - The informational widget contained in the tile. For example - an ``XyChart``. - """ - - x_pos = proto.Field( - proto.INT32, - number=1, - ) - y_pos = proto.Field( - proto.INT32, - number=2, - ) - width = proto.Field( - proto.INT32, - number=3, - ) - height = proto.Field( - proto.INT32, - number=4, - ) - widget = proto.Field( - proto.MESSAGE, - number=5, - message=gmd_widget.Widget, - ) - - columns = proto.Field( - proto.INT32, - number=1, - ) - tiles = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Tile, - ) - - -class RowLayout(proto.Message): - r"""A simplified layout that divides the available space into - rows and arranges a set of widgets horizontally in each row. - - Attributes: - rows (Sequence[google.monitoring.dashboard_v1.types.RowLayout.Row]): - The rows of content to display. - """ - - class Row(proto.Message): - r"""Defines the layout properties and content for a row. - Attributes: - weight (int): - The relative weight of this row. The row - weight is used to adjust the height of rows on - the screen (relative to peers). Greater the - weight, greater the height of the row on the - screen. If omitted, a value of 1 is used while - rendering. - widgets (Sequence[google.monitoring.dashboard_v1.types.Widget]): - The display widgets arranged horizontally in - this row. - """ - - weight = proto.Field( - proto.INT64, - number=1, - ) - widgets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gmd_widget.Widget, - ) - - rows = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Row, - ) - - -class ColumnLayout(proto.Message): - r"""A simplified layout that divides the available space into - vertical columns and arranges a set of widgets vertically in - each column. - - Attributes: - columns (Sequence[google.monitoring.dashboard_v1.types.ColumnLayout.Column]): - The columns of content to display. - """ - - class Column(proto.Message): - r"""Defines the layout properties and content for a column. - Attributes: - weight (int): - The relative weight of this column. The - column weight is used to adjust the width of - columns on the screen (relative to peers). - Greater the weight, greater the width of the - column on the screen. If omitted, a value of 1 - is used while rendering. - widgets (Sequence[google.monitoring.dashboard_v1.types.Widget]): - The display widgets arranged vertically in - this column. - """ - - weight = proto.Field( - proto.INT64, - number=1, - ) - widgets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gmd_widget.Widget, - ) - - columns = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Column, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py deleted file mode 100644 index f37f64e..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/metrics.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import common - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'SparkChartType', - 'TimeSeriesQuery', - 'TimeSeriesFilter', - 'TimeSeriesFilterRatio', - 'Threshold', - }, -) - - -class SparkChartType(proto.Enum): - r"""Defines the possible types of spark chart supported by the - ``Scorecard``. - """ - SPARK_CHART_TYPE_UNSPECIFIED = 0 - SPARK_LINE = 1 - SPARK_BAR = 2 - - -class TimeSeriesQuery(proto.Message): - r"""TimeSeriesQuery collects the set of supported methods for - querying time series data from the Stackdriver metrics API. - - Attributes: - time_series_filter (google.monitoring.dashboard_v1.types.TimeSeriesFilter): - Filter parameters to fetch time series. - time_series_filter_ratio (google.monitoring.dashboard_v1.types.TimeSeriesFilterRatio): - Parameters to fetch a ratio between two time - series filters. - time_series_query_language (str): - A query used to fetch time series. - unit_override (str): - The unit of data contained in fetched time series. If - non-empty, this unit will override any unit that accompanies - fetched data. The format is the same as the - ```unit`` `__ - field in ``MetricDescriptor``. - """ - - time_series_filter = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='TimeSeriesFilter', - ) - time_series_filter_ratio = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='TimeSeriesFilterRatio', - ) - time_series_query_language = proto.Field( - proto.STRING, - number=3, - oneof='source', - ) - unit_override = proto.Field( - proto.STRING, - number=5, - ) - - -class TimeSeriesFilter(proto.Message): - r"""A filter that defines a subset of time series data that is displayed - in a widget. Time series data is fetched using the - ```ListTimeSeries`` `__ - method. - - Attributes: - filter (str): - Required. The `monitoring - filter `__ - that identifies the metric types, resources, and projects to - query. - aggregation (google.monitoring.dashboard_v1.types.Aggregation): - By default, the raw time series data is - returned. Use this field to combine multiple - time series for different views of the data. - secondary_aggregation (google.monitoring.dashboard_v1.types.Aggregation): - Apply a second aggregation after ``aggregation`` is applied. - pick_time_series_filter (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter): - Ranking based time series filter. - statistical_time_series_filter (google.monitoring.dashboard_v1.types.StatisticalTimeSeriesFilter): - Statistics based time series filter. - Note: This field is deprecated and completely - ignored by the API. - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - aggregation = proto.Field( - proto.MESSAGE, - number=2, - message=common.Aggregation, - ) - secondary_aggregation = proto.Field( - proto.MESSAGE, - number=3, - message=common.Aggregation, - ) - pick_time_series_filter = proto.Field( - proto.MESSAGE, - number=4, - oneof='output_filter', - message=common.PickTimeSeriesFilter, - ) - statistical_time_series_filter = proto.Field( - proto.MESSAGE, - number=5, - oneof='output_filter', - message=common.StatisticalTimeSeriesFilter, - ) - - -class TimeSeriesFilterRatio(proto.Message): - r"""A pair of time series filters that define a ratio - computation. The output time series is the pair-wise division of - each aligned element from the numerator and denominator time - series. - - Attributes: - numerator (google.monitoring.dashboard_v1.types.TimeSeriesFilterRatio.RatioPart): - The numerator of the ratio. - denominator (google.monitoring.dashboard_v1.types.TimeSeriesFilterRatio.RatioPart): - The denominator of the ratio. - secondary_aggregation (google.monitoring.dashboard_v1.types.Aggregation): - Apply a second aggregation after the ratio is - computed. - pick_time_series_filter (google.monitoring.dashboard_v1.types.PickTimeSeriesFilter): - Ranking based time series filter. - statistical_time_series_filter (google.monitoring.dashboard_v1.types.StatisticalTimeSeriesFilter): - Statistics based time series filter. - Note: This field is deprecated and completely - ignored by the API. - """ - - class RatioPart(proto.Message): - r"""Describes a query to build the numerator or denominator of a - TimeSeriesFilterRatio. - - Attributes: - filter (str): - Required. The `monitoring - filter `__ - that identifies the metric types, resources, and projects to - query. - aggregation (google.monitoring.dashboard_v1.types.Aggregation): - By default, the raw time series data is - returned. Use this field to combine multiple - time series for different views of the data. - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - aggregation = proto.Field( - proto.MESSAGE, - number=2, - message=common.Aggregation, - ) - - numerator = proto.Field( - proto.MESSAGE, - number=1, - message=RatioPart, - ) - denominator = proto.Field( - proto.MESSAGE, - number=2, - message=RatioPart, - ) - secondary_aggregation = proto.Field( - proto.MESSAGE, - number=3, - message=common.Aggregation, - ) - pick_time_series_filter = proto.Field( - proto.MESSAGE, - number=4, - oneof='output_filter', - message=common.PickTimeSeriesFilter, - ) - statistical_time_series_filter = proto.Field( - proto.MESSAGE, - number=5, - oneof='output_filter', - message=common.StatisticalTimeSeriesFilter, - ) - - -class Threshold(proto.Message): - r"""Defines a threshold for categorizing time series values. - Attributes: - label (str): - A label for the threshold. - value (float): - The value of the threshold. The value should - be defined in the native scale of the metric. - color (google.monitoring.dashboard_v1.types.Threshold.Color): - The state color for this threshold. Color is - not allowed in a XyChart. - direction (google.monitoring.dashboard_v1.types.Threshold.Direction): - The direction for the current threshold. - Direction is not allowed in a XyChart. - """ - class Color(proto.Enum): - r"""The color suggests an interpretation to the viewer when - actual values cross the threshold. Comments on each color - provide UX guidance on how users can be expected to interpret a - given state color. - """ - COLOR_UNSPECIFIED = 0 - YELLOW = 4 - RED = 6 - - class Direction(proto.Enum): - r"""Whether the threshold is considered crossed by an actual - value above or below its threshold value. - """ - DIRECTION_UNSPECIFIED = 0 - ABOVE = 1 - BELOW = 2 - - label = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.DOUBLE, - number=2, - ) - color = proto.Field( - proto.ENUM, - number=3, - enum=Color, - ) - direction = proto.Field( - proto.ENUM, - number=4, - enum=Direction, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py deleted file mode 100644 index c0fcd23..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/scorecard.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import metrics -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'Scorecard', - }, -) - - -class Scorecard(proto.Message): - r"""A widget showing the latest value of a metric, and how this - value relates to one or more thresholds. - - Attributes: - time_series_query (google.monitoring.dashboard_v1.types.TimeSeriesQuery): - Required. Fields for querying time series - data from the Stackdriver metrics API. - gauge_view (google.monitoring.dashboard_v1.types.Scorecard.GaugeView): - Will cause the scorecard to show a gauge - chart. - spark_chart_view (google.monitoring.dashboard_v1.types.Scorecard.SparkChartView): - Will cause the scorecard to show a spark - chart. - thresholds (Sequence[google.monitoring.dashboard_v1.types.Threshold]): - The thresholds used to determine the state of - the scorecard given the time series' current - value. For an actual value x, the scorecard is - in a danger state if x is less than or equal to - a danger threshold that triggers below, or - greater than or equal to a danger threshold that - triggers above. Similarly, if x is above/below a - warning threshold that triggers above/below, - then the scorecard is in a warning state - - unless x also puts it in a danger state. (Danger - trumps warning.) - As an example, consider a scorecard with the - following four thresholds: { - value: 90, - category: 'DANGER', - trigger: 'ABOVE', - }, - { - value: 70, - category: 'WARNING', - trigger: 'ABOVE', - }, - { - value: 10, - category: 'DANGER', - trigger: 'BELOW', - }, - { - value: 20, - category: 'WARNING', - trigger: 'BELOW', - } - - Then: values less than or equal to 10 would put - the scorecard in a DANGER state, values greater - than 10 but less than or equal to 20 a WARNING - state, values strictly between 20 and 70 an OK - state, values greater than or equal to 70 but - less than 90 a WARNING state, and values greater - than or equal to 90 a DANGER state. - """ - - class GaugeView(proto.Message): - r"""A gauge chart shows where the current value sits within a - pre-defined range. The upper and lower bounds should define the - possible range of values for the scorecard's query (inclusive). - - Attributes: - lower_bound (float): - The lower bound for this gauge chart. The - value of the chart should always be greater than - or equal to this. - upper_bound (float): - The upper bound for this gauge chart. The - value of the chart should always be less than or - equal to this. - """ - - lower_bound = proto.Field( - proto.DOUBLE, - number=1, - ) - upper_bound = proto.Field( - proto.DOUBLE, - number=2, - ) - - class SparkChartView(proto.Message): - r"""A sparkChart is a small chart suitable for inclusion in a - table-cell or inline in text. This message contains the - configuration for a sparkChart to show up on a Scorecard, - showing recent trends of the scorecard's timeseries. - - Attributes: - spark_chart_type (google.monitoring.dashboard_v1.types.SparkChartType): - Required. The type of sparkchart to show in - this chartView. - min_alignment_period (google.protobuf.duration_pb2.Duration): - The lower bound on data point frequency in - the chart implemented by specifying the minimum - alignment period to use in a time series query. - For example, if the data is published once every - 10 minutes it would not make sense to fetch and - align data at one minute intervals. This field - is optional and exists only as a hint. - """ - - spark_chart_type = proto.Field( - proto.ENUM, - number=1, - enum=metrics.SparkChartType, - ) - min_alignment_period = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - time_series_query = proto.Field( - proto.MESSAGE, - number=1, - message=metrics.TimeSeriesQuery, - ) - gauge_view = proto.Field( - proto.MESSAGE, - number=4, - oneof='data_view', - message=GaugeView, - ) - spark_chart_view = proto.Field( - proto.MESSAGE, - number=5, - oneof='data_view', - message=SparkChartView, - ) - thresholds = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=metrics.Threshold, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py deleted file mode 100644 index 041e5fd..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/service.py +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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. -# - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py deleted file mode 100644 index 031f733..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/text.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'Text', - }, -) - - -class Text(proto.Message): - r"""A widget that displays textual content. - Attributes: - content (str): - The text content to be displayed. - format_ (google.monitoring.dashboard_v1.types.Text.Format): - How the text content is formatted. - """ - class Format(proto.Enum): - r"""The format type of the text content.""" - FORMAT_UNSPECIFIED = 0 - MARKDOWN = 1 - RAW = 2 - - content = proto.Field( - proto.STRING, - number=1, - ) - format_ = proto.Field( - proto.ENUM, - number=2, - enum=Format, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py deleted file mode 100644 index 15a957c..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/widget.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import scorecard as gmd_scorecard -from google.monitoring.dashboard_v1.types import text as gmd_text -from google.monitoring.dashboard_v1.types import xychart -from google.protobuf import empty_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'Widget', - }, -) - - -class Widget(proto.Message): - r"""Widget contains a single dashboard component and - configuration of how to present the component in the dashboard. - - Attributes: - title (str): - Optional. The title of the widget. - xy_chart (google.monitoring.dashboard_v1.types.XyChart): - A chart of time series data. - scorecard (google.monitoring.dashboard_v1.types.Scorecard): - A scorecard summarizing time series data. - text (google.monitoring.dashboard_v1.types.Text): - A raw string or markdown displaying textual - content. - blank (google.protobuf.empty_pb2.Empty): - A blank space. - """ - - title = proto.Field( - proto.STRING, - number=1, - ) - xy_chart = proto.Field( - proto.MESSAGE, - number=2, - oneof='content', - message=xychart.XyChart, - ) - scorecard = proto.Field( - proto.MESSAGE, - number=3, - oneof='content', - message=gmd_scorecard.Scorecard, - ) - text = proto.Field( - proto.MESSAGE, - number=4, - oneof='content', - message=gmd_text.Text, - ) - blank = proto.Field( - proto.MESSAGE, - number=5, - oneof='content', - message=empty_pb2.Empty, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py b/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py deleted file mode 100644 index ddddc57..0000000 --- a/owl-bot-staging/v1/google/monitoring/dashboard_v1/types/xychart.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.monitoring.dashboard_v1.types import metrics -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.monitoring.dashboard.v1', - manifest={ - 'XyChart', - 'ChartOptions', - }, -) - - -class XyChart(proto.Message): - r"""A chart that displays data on a 2D (X and Y axes) plane. - Attributes: - data_sets (Sequence[google.monitoring.dashboard_v1.types.XyChart.DataSet]): - Required. The data displayed in this chart. - timeshift_duration (google.protobuf.duration_pb2.Duration): - The duration used to display a comparison - chart. A comparison chart simultaneously shows - values from two similar-length time periods - (e.g., week-over-week metrics). - The duration must be positive, and it can only - be applied to charts with data sets of LINE plot - type. - thresholds (Sequence[google.monitoring.dashboard_v1.types.Threshold]): - Threshold lines drawn horizontally across the - chart. - x_axis (google.monitoring.dashboard_v1.types.XyChart.Axis): - The properties applied to the X axis. - y_axis (google.monitoring.dashboard_v1.types.XyChart.Axis): - The properties applied to the Y axis. - chart_options (google.monitoring.dashboard_v1.types.ChartOptions): - Display options for the chart. - """ - - class DataSet(proto.Message): - r"""Groups a time series query definition with charting options. - Attributes: - time_series_query (google.monitoring.dashboard_v1.types.TimeSeriesQuery): - Required. Fields for querying time series - data from the Stackdriver metrics API. - plot_type (google.monitoring.dashboard_v1.types.XyChart.DataSet.PlotType): - How this data should be plotted on the chart. - legend_template (str): - A template string for naming ``TimeSeries`` in the resulting - data set. This should be a string with interpolations of the - form ``${label_name}``, which will resolve to the label's - value. - min_alignment_period (google.protobuf.duration_pb2.Duration): - Optional. The lower bound on data point frequency for this - data set, implemented by specifying the minimum alignment - period to use in a time series query. For example, if the - data is published once every 10 minutes, the - ``min_alignment_period`` should be at least 10 minutes. It - would not make sense to fetch and align data at one minute - intervals. - """ - class PlotType(proto.Enum): - r"""The types of plotting strategies for data sets.""" - PLOT_TYPE_UNSPECIFIED = 0 - LINE = 1 - STACKED_AREA = 2 - STACKED_BAR = 3 - HEATMAP = 4 - - time_series_query = proto.Field( - proto.MESSAGE, - number=1, - message=metrics.TimeSeriesQuery, - ) - plot_type = proto.Field( - proto.ENUM, - number=2, - enum='XyChart.DataSet.PlotType', - ) - legend_template = proto.Field( - proto.STRING, - number=3, - ) - min_alignment_period = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - - class Axis(proto.Message): - r"""A chart axis. - Attributes: - label (str): - The label of the axis. - scale (google.monitoring.dashboard_v1.types.XyChart.Axis.Scale): - The axis scale. By default, a linear scale is - used. - """ - class Scale(proto.Enum): - r"""Types of scales used in axes.""" - SCALE_UNSPECIFIED = 0 - LINEAR = 1 - LOG10 = 2 - - label = proto.Field( - proto.STRING, - number=1, - ) - scale = proto.Field( - proto.ENUM, - number=2, - enum='XyChart.Axis.Scale', - ) - - data_sets = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=DataSet, - ) - timeshift_duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - thresholds = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=metrics.Threshold, - ) - x_axis = proto.Field( - proto.MESSAGE, - number=6, - message=Axis, - ) - y_axis = proto.Field( - proto.MESSAGE, - number=7, - message=Axis, - ) - chart_options = proto.Field( - proto.MESSAGE, - number=8, - message='ChartOptions', - ) - - -class ChartOptions(proto.Message): - r"""Options to control visual rendering of a chart. - Attributes: - mode (google.monitoring.dashboard_v1.types.ChartOptions.Mode): - The chart mode. - """ - class Mode(proto.Enum): - r"""Chart mode options.""" - MODE_UNSPECIFIED = 0 - COLOR = 1 - X_RAY = 2 - STATS = 3 - - mode = proto.Field( - proto.ENUM, - number=1, - enum=Mode, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 6a8f47f..0000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/monitoring/dashboard_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py deleted file mode 100644 index db3aefd..0000000 --- a/owl-bot-staging/v1/scripts/fixup_dashboard_v1_keywords.py +++ /dev/null @@ -1,180 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class dashboardCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_dashboard': ('parent', 'dashboard', ), - 'delete_dashboard': ('name', ), - 'get_dashboard': ('name', ), - 'list_dashboards': ('parent', 'page_size', 'page_token', ), - 'update_dashboard': ('dashboard', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=dashboardCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the dashboard client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 85a0d6f..0000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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 io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-monitoring-dashboard', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.monitoring'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py b/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py deleted file mode 100644 index 8edb05d..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/dashboard_v1/test_dashboards_service.py +++ /dev/null @@ -1,1924 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.monitoring.dashboard_v1.services.dashboards_service import DashboardsServiceAsyncClient -from google.monitoring.dashboard_v1.services.dashboards_service import DashboardsServiceClient -from google.monitoring.dashboard_v1.services.dashboards_service import pagers -from google.monitoring.dashboard_v1.services.dashboards_service import transports -from google.monitoring.dashboard_v1.services.dashboards_service.transports.base import _GOOGLE_AUTH_VERSION -from google.monitoring.dashboard_v1.types import common -from google.monitoring.dashboard_v1.types import dashboard -from google.monitoring.dashboard_v1.types import dashboards_service -from google.monitoring.dashboard_v1.types import layouts -from google.monitoring.dashboard_v1.types import metrics -from google.monitoring.dashboard_v1.types import scorecard -from google.monitoring.dashboard_v1.types import text -from google.monitoring.dashboard_v1.types import widget -from google.monitoring.dashboard_v1.types import xychart -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DashboardsServiceClient._get_default_mtls_endpoint(None) is None - assert DashboardsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DashboardsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DashboardsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DashboardsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DashboardsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - DashboardsServiceClient, - DashboardsServiceAsyncClient, -]) -def test_dashboards_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'monitoring.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - DashboardsServiceClient, - DashboardsServiceAsyncClient, -]) -def test_dashboards_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_called_with(True) - - -@pytest.mark.parametrize("client_class", [ - DashboardsServiceClient, - DashboardsServiceAsyncClient, -]) -def test_dashboards_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'monitoring.googleapis.com:443' - - -def test_dashboards_service_client_get_transport_class(): - transport = DashboardsServiceClient.get_transport_class() - available_transports = [ - transports.DashboardsServiceGrpcTransport, - ] - assert transport in available_transports - - transport = DashboardsServiceClient.get_transport_class("grpc") - assert transport == transports.DashboardsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), - (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(DashboardsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceClient)) -@mock.patch.object(DashboardsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceAsyncClient)) -def test_dashboards_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(DashboardsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(DashboardsServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc", "true"), - (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc", "false"), - (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(DashboardsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceClient)) -@mock.patch.object(DashboardsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DashboardsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_dashboards_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), - (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_dashboards_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DashboardsServiceClient, transports.DashboardsServiceGrpcTransport, "grpc"), - (DashboardsServiceAsyncClient, transports.DashboardsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_dashboards_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_dashboards_service_client_client_options_from_dict(): - with mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DashboardsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_create_dashboard(transport: str = 'grpc', request_type=dashboards_service.CreateDashboardRequest): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dashboard.Dashboard( - name='name_value', - display_name='display_name_value', - etag='etag_value', - grid_layout=layouts.GridLayout(columns=769), - ) - response = client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.CreateDashboardRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dashboard.Dashboard) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -def test_create_dashboard_from_dict(): - test_create_dashboard(request_type=dict) - - -def test_create_dashboard_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dashboard), - '__call__') as call: - client.create_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.CreateDashboardRequest() - - -@pytest.mark.asyncio -async def test_create_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.CreateDashboardRequest): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard( - name='name_value', - display_name='display_name_value', - etag='etag_value', - )) - response = await client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.CreateDashboardRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dashboard.Dashboard) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_create_dashboard_async_from_dict(): - await test_create_dashboard_async(request_type=dict) - - -def test_create_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.CreateDashboardRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dashboard), - '__call__') as call: - call.return_value = dashboard.Dashboard() - client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.CreateDashboardRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dashboard), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) - await client.create_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_dashboards(transport: str = 'grpc', request_type=dashboards_service.ListDashboardsRequest): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dashboards_service.ListDashboardsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.ListDashboardsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDashboardsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_dashboards_from_dict(): - test_list_dashboards(request_type=dict) - - -def test_list_dashboards_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__') as call: - client.list_dashboards() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.ListDashboardsRequest() - - -@pytest.mark.asyncio -async def test_list_dashboards_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.ListDashboardsRequest): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboards_service.ListDashboardsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.ListDashboardsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDashboardsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_dashboards_async_from_dict(): - await test_list_dashboards_async(request_type=dict) - - -def test_list_dashboards_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.ListDashboardsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__') as call: - call.return_value = dashboards_service.ListDashboardsResponse() - client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_dashboards_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.ListDashboardsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboards_service.ListDashboardsResponse()) - await client.list_dashboards(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_dashboards_pager(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - next_page_token='abc', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[], - next_page_token='def', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - ], - next_page_token='ghi', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_dashboards(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, dashboard.Dashboard) - for i in results) - -def test_list_dashboards_pages(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - next_page_token='abc', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[], - next_page_token='def', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - ], - next_page_token='ghi', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - ), - RuntimeError, - ) - pages = list(client.list_dashboards(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_dashboards_async_pager(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - next_page_token='abc', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[], - next_page_token='def', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - ], - next_page_token='ghi', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_dashboards(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, dashboard.Dashboard) - for i in responses) - -@pytest.mark.asyncio -async def test_list_dashboards_async_pages(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_dashboards), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - next_page_token='abc', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[], - next_page_token='def', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - ], - next_page_token='ghi', - ), - dashboards_service.ListDashboardsResponse( - dashboards=[ - dashboard.Dashboard(), - dashboard.Dashboard(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_dashboards(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_dashboard(transport: str = 'grpc', request_type=dashboards_service.GetDashboardRequest): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dashboard.Dashboard( - name='name_value', - display_name='display_name_value', - etag='etag_value', - grid_layout=layouts.GridLayout(columns=769), - ) - response = client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.GetDashboardRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dashboard.Dashboard) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -def test_get_dashboard_from_dict(): - test_get_dashboard(request_type=dict) - - -def test_get_dashboard_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dashboard), - '__call__') as call: - client.get_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.GetDashboardRequest() - - -@pytest.mark.asyncio -async def test_get_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.GetDashboardRequest): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard( - name='name_value', - display_name='display_name_value', - etag='etag_value', - )) - response = await client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.GetDashboardRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dashboard.Dashboard) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_dashboard_async_from_dict(): - await test_get_dashboard_async(request_type=dict) - - -def test_get_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.GetDashboardRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dashboard), - '__call__') as call: - call.return_value = dashboard.Dashboard() - client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.GetDashboardRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_dashboard), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) - await client.get_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_dashboard(transport: str = 'grpc', request_type=dashboards_service.DeleteDashboardRequest): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.DeleteDashboardRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_dashboard_from_dict(): - test_delete_dashboard(request_type=dict) - - -def test_delete_dashboard_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dashboard), - '__call__') as call: - client.delete_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.DeleteDashboardRequest() - - -@pytest.mark.asyncio -async def test_delete_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.DeleteDashboardRequest): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.DeleteDashboardRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_dashboard_async_from_dict(): - await test_delete_dashboard_async(request_type=dict) - - -def test_delete_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.DeleteDashboardRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dashboard), - '__call__') as call: - call.return_value = None - client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.DeleteDashboardRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_dashboard), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_update_dashboard(transport: str = 'grpc', request_type=dashboards_service.UpdateDashboardRequest): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = dashboard.Dashboard( - name='name_value', - display_name='display_name_value', - etag='etag_value', - grid_layout=layouts.GridLayout(columns=769), - ) - response = client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.UpdateDashboardRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dashboard.Dashboard) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -def test_update_dashboard_from_dict(): - test_update_dashboard(request_type=dict) - - -def test_update_dashboard_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dashboard), - '__call__') as call: - client.update_dashboard() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.UpdateDashboardRequest() - - -@pytest.mark.asyncio -async def test_update_dashboard_async(transport: str = 'grpc_asyncio', request_type=dashboards_service.UpdateDashboardRequest): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dashboard), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard( - name='name_value', - display_name='display_name_value', - etag='etag_value', - )) - response = await client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == dashboards_service.UpdateDashboardRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, dashboard.Dashboard) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_update_dashboard_async_from_dict(): - await test_update_dashboard_async(request_type=dict) - - -def test_update_dashboard_field_headers(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.UpdateDashboardRequest() - - request.dashboard.name = 'dashboard.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dashboard), - '__call__') as call: - call.return_value = dashboard.Dashboard() - client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'dashboard.name=dashboard.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_dashboard_field_headers_async(): - client = DashboardsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = dashboards_service.UpdateDashboardRequest() - - request.dashboard.name = 'dashboard.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_dashboard), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) - await client.update_dashboard(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'dashboard.name=dashboard.name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DashboardsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DashboardsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DashboardsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DashboardsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DashboardsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DashboardsServiceGrpcTransport, - ) - -def test_dashboards_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DashboardsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_dashboards_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DashboardsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_dashboard', - 'list_dashboards', - 'get_dashboard', - 'delete_dashboard', - 'update_dashboard', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_dashboards_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DashboardsServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_dashboards_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DashboardsServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ), - quota_project_id="octopus", - ) - - -def test_dashboards_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.monitoring.dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DashboardsServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_dashboards_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DashboardsServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_dashboards_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DashboardsServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read', 'https://www.googleapis.com/auth/monitoring.write',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_dashboards_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read', 'https://www.googleapis.com/auth/monitoring.write',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DashboardsServiceGrpcTransport, - transports.DashboardsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_dashboards_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DashboardsServiceGrpcTransport, grpc_helpers), - (transports.DashboardsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_dashboards_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "monitoring.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', -), - scopes=["1", "2"], - default_host="monitoring.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport]) -def test_dashboards_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_dashboards_service_host_no_port(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='monitoring.googleapis.com'), - ) - assert client.transport._host == 'monitoring.googleapis.com:443' - - -def test_dashboards_service_host_with_port(): - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='monitoring.googleapis.com:8000'), - ) - assert client.transport._host == 'monitoring.googleapis.com:8000' - -def test_dashboards_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DashboardsServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_dashboards_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DashboardsServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport]) -def test_dashboards_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DashboardsServiceGrpcTransport, transports.DashboardsServiceGrpcAsyncIOTransport]) -def test_dashboards_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_dashboard_path(): - project = "squid" - dashboard = "clam" - expected = "projects/{project}/dashboards/{dashboard}".format(project=project, dashboard=dashboard, ) - actual = DashboardsServiceClient.dashboard_path(project, dashboard) - assert expected == actual - - -def test_parse_dashboard_path(): - expected = { - "project": "whelk", - "dashboard": "octopus", - } - path = DashboardsServiceClient.dashboard_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_dashboard_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DashboardsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = DashboardsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = DashboardsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = DashboardsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DashboardsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = DashboardsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = DashboardsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = DashboardsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DashboardsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = DashboardsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DashboardsServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DashboardsServiceTransport, '_prep_wrapped_messages') as prep: - client = DashboardsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DashboardsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DashboardsServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dashboard_v1/test_dashboards_service.py b/tests/unit/gapic/dashboard_v1/test_dashboards_service.py index 2b6c847..f799b11 100644 --- a/tests/unit/gapic/dashboard_v1/test_dashboards_service.py +++ b/tests/unit/gapic/dashboard_v1/test_dashboards_service.py @@ -39,9 +39,6 @@ ) from google.cloud.monitoring_dashboard_v1.services.dashboards_service import pagers from google.cloud.monitoring_dashboard_v1.services.dashboards_service import transports -from google.cloud.monitoring_dashboard_v1.services.dashboards_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.monitoring_dashboard_v1.services.dashboards_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -59,8 +56,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -71,16 +69,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -144,6 +132,18 @@ def test_dashboards_service_client_from_service_account_info(client_class): assert client.transport._host == "monitoring.googleapis.com:443" +@pytest.mark.parametrize( + "client_class", [DashboardsServiceClient, DashboardsServiceAsyncClient,] +) +def test_dashboards_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_called_with(True) + + @pytest.mark.parametrize( "client_class", [DashboardsServiceClient, DashboardsServiceAsyncClient,] ) @@ -1611,7 +1611,6 @@ def test_dashboards_service_transport_auth_adc_old_google_auth(transport_class): (transports.DashboardsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 def test_dashboards_service_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -1645,84 +1644,6 @@ def test_dashboards_service_transport_create_channel(transport_class, grpc_helpe ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DashboardsServiceGrpcTransport, grpc_helpers), - (transports.DashboardsServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_dashboards_service_transport_create_channel_old_api_core( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "monitoring.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DashboardsServiceGrpcTransport, grpc_helpers), - (transports.DashboardsServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_dashboards_service_transport_create_channel_user_scopes( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "monitoring.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ From 2824e79bdd005a2b89e3ba5ce26eb64732838d0e Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Tue, 22 Jun 2021 23:02:15 +0000 Subject: [PATCH 3/4] fix: require google-api-core>=1.26.0 --- setup.py | 2 +- testing/constraints-3.6.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 0dbf1dc..ccfe6fa 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ version = "2.1.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "google-api-core[grpc] >= 1.26.0, <2.0.0dev"," "proto-plus >= 0.4.0", "packaging >= 14.3", ] diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 4b0d32c..b237c54 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -5,7 +5,7 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.22.2 +google-api-core==1.26.0 proto-plus==0.4.0 libcst==0.2.5 packaging==14.3 From 55e4a0e6f448b9611c5d487d4d7288a01653371f Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Tue, 22 Jun 2021 23:11:22 +0000 Subject: [PATCH 4/4] fix: fix typo in setup.py --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index ccfe6fa..f89d05a 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ version = "2.1.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.26.0, <2.0.0dev"," + "google-api-core[grpc] >= 1.26.0, <2.0.0dev", "proto-plus >= 0.4.0", "packaging >= 14.3", ]